-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathrest-server.ts
More file actions
3245 lines (3100 loc) · 151 KB
/
rest-server.ts
File metadata and controls
3245 lines (3100 loc) · 151 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 { IHttpServer } from '@objectstack/core';
import { RouteManager } from './route-manager.js';
import { RestServerConfig, RestApiConfig, CrudEndpointsConfig, MetadataEndpointsConfig, BatchEndpointsConfig, RouteGenerationConfig } from '@objectstack/spec/api';
import { ObjectStackProtocol } from '@objectstack/spec/api';
// Node-safe logger — avoids importing 'console' which is absent from ES2020 lib typings.
const logError = (...args: unknown[]) => (globalThis as any).console?.error(...args);
/**
* Map a data-layer error to a clean HTTP response. Unknown-object errors
* (SQLite "no such table", PG "relation does not exist", protocol
* "object not found", etc.) are surfaced as a 404 with `code: 'object_not_found'`
* so clients can distinguish "object isn't registered" from real server
* faults. Anything else becomes a 400 (bad request) preserving prior
* behavior. Genuine 500s are still logged.
*
* `PermissionDeniedError` (thrown by `SecurityPlugin`) MUST be caught
* before the unknown-object heuristic, otherwise its message —
* "[Security] Access denied: operation 'insert' on object 'sys_user' is
* not permitted …" — trips the `'<obj>' … not` substring check and
* returns a misleading 404.
*/
function mapDataError(error: any, object?: string): { status: number; body: Record<string, unknown> } {
// Validation failures → 400 with per-field envelope. Handled FIRST
// because the validator throws a typed error before any SQL ever
// runs, and we want callers to differentiate "your payload was
// invalid" (fixable client-side) from generic 400s.
if (error?.code === 'VALIDATION_FAILED' || error?.name === 'ValidationError') {
return {
status: 400,
body: {
error: error?.message ?? 'Validation failed',
code: 'VALIDATION_FAILED',
fields: Array.isArray(error?.fields) ? error.fields : [],
...(object ? { object } : {}),
},
};
}
// Short-circuit: explicit security denial → 403. Match by `code` /
// `name` to avoid pulling a runtime dependency on plugin-security.
if (
error?.code === 'PERMISSION_DENIED' ||
error?.name === 'PermissionDeniedError' ||
(typeof error?.message === 'string' && error.message.startsWith('[Security] Access denied'))
) {
return {
status: 403,
body: {
error: error?.message ?? 'Permission denied',
code: 'PERMISSION_DENIED',
...(object ? { object } : {}),
},
};
}
const raw = String(error?.message ?? error ?? '');
const lower = raw.toLowerCase();
// ProjectKernelFactory: project missing database_url/driver — typically
// means provisioning is in flight or the project record was never
// fully provisioned. 503 (with Retry-After implied) is more accurate
// than the default 400/500: clients can poll until the project is
// active.
if (
raw.includes('[ProjectKernelFactory]') &&
(lower.includes('missing database_url') || lower.includes('not found'))
) {
const isProvisioning = lower.includes("status='provisioning'") || lower.includes("status='pending'");
const isFailed = lower.includes("status='failed'");
return {
status: isProvisioning ? 503 : isFailed ? 502 : 404,
body: {
error: raw,
code: isProvisioning
? 'PROJECT_PROVISIONING'
: isFailed
? 'PROJECT_PROVISIONING_FAILED'
: 'PROJECT_NOT_FOUND',
},
};
}
// Record-level not-found from ObjectQL (`getData` / `updateData` /
// `deleteData`). These are normal client mistakes (stale UI link,
// hand-typed id, deleted record) and should be a quiet 404 — not
// a "[REST] Unhandled error" log entry that scares operators.
if (
error?.code === 'RECORD_NOT_FOUND' ||
/^Record\s+\S+\s+not found in\s+\S+/i.test(raw)
) {
return {
status: 404,
body: {
error: raw,
code: 'RECORD_NOT_FOUND',
...(object ? { object } : {}),
},
};
}
const looksLikeUnknownObject =
lower.includes('no such table') ||
lower.includes('relation') && lower.includes('does not exist') ||
lower.includes('table not found') ||
lower.includes('unknown object') ||
lower.includes('object not found') ||
lower.includes('no driver available') ||
(object !== undefined && lower.includes(`'${object.toLowerCase()}'`) && lower.includes('not'));
if (looksLikeUnknownObject) {
return {
status: 404,
body: {
error: object ? `Object '${object}' is not registered` : 'Object not found',
code: 'object_not_found',
object,
},
};
}
// Default: do NOT leak raw SQL or driver internals. If the message
// looks like a SQL/driver dump, replace it with a generic envelope
// and rely on server logs for the full diagnostic.
const looksLikeSqlLeak =
lower.includes('sqlite_') ||
lower.includes('sqlstate') ||
lower.startsWith('insert into ') ||
lower.startsWith('update ') ||
lower.startsWith('select ') ||
lower.startsWith('delete from ') ||
lower.includes('constraint failed') ||
lower.includes('unique constraint') ||
lower.includes('foreign key');
if (looksLikeSqlLeak) {
// Surface unique-constraint violations as a structured 409 so
// the UI can map them to "this value already exists".
if (lower.includes('unique constraint') || lower.includes('unique violation')) {
return {
status: 409,
body: {
error: 'A record with this value already exists',
code: 'UNIQUE_VIOLATION',
...(object ? { object } : {}),
},
};
}
return {
status: 500,
body: { error: 'Internal data error', code: 'DATABASE_ERROR' },
};
}
return { status: 400, body: { error: raw || 'Bad request' } };
}
/**
* Centralized error responder for all REST handlers. Ensures raw driver
* messages (SQLite/Postgres dumps, stack traces, unique-constraint
* payloads with table names, etc.) never reach clients. Honors
* structured errors that already carry an explicit `status` so callers
* can surface domain-specific codes (e.g. 422 from a metadata save
* validator), and routes everything else through `mapDataError` so the
* security / validation / SQL-leak / unknown-object envelopes apply
* uniformly across CRUD, batch, metadata, UI and discovery routes.
*/
function sendError(res: any, error: any, object?: string): void {
if (typeof error?.status === 'number' && error.status >= 400 && error.status < 600) {
const safeMsg = typeof error.message === 'string' && error.message.length < 500
? error.message
: 'Request failed';
res.status(error.status).json({
error: safeMsg,
...(error.code ? { code: error.code } : {}),
});
return;
}
const mapped = mapDataError(error, object);
res.status(mapped.status).json(mapped.body);
}
/**
* Whether a mapped data-error status represents an *expected* client/lifecycle
* outcome (and therefore shouldn't be logged as "[REST] Unhandled error").
* - 403 PERMISSION_DENIED is a normal RBAC denial
* - 404 unknown object / project not found is a normal client mistake
* - 502/503 mean the underlying project is provisioning or failed; the
* handler will emit the response and the operator can inspect
* sys_project.metadata.provisioningError if needed.
*/
function isExpectedDataStatus(status: number): boolean {
return status === 403 || status === 404 || status === 409 || status === 502 || status === 503;
}
/**
* Minimal RFC-4180-style CSV parser used by the bulk-import endpoint
* (M10.9). Handles quoted fields (including embedded quotes via "" and
* embedded commas/newlines) and both CRLF and LF line endings.
*
* The first non-empty line is treated as the header row. Header names
* can be re-mapped to canonical field names via the optional `mapping`
* argument (e.g. `{ "First Name": "first_name" }`); unmapped headers
* pass through unchanged. Empty cells become empty strings.
*
* Kept dependency-free so REST stays runtime-portable (Hono / Express
* adapters both consume this without pulling a CSV lib transitively).
*/
function parseCsvToRows(csv: string, mapping: Record<string, string> = {}): Array<Record<string, any>> {
const text = csv.replace(/^\uFEFF/, ''); // strip BOM
const cells: string[][] = [];
let cur = '';
let row: string[] = [];
let inQuotes = false;
for (let i = 0; i < text.length; i++) {
const ch = text[i];
if (inQuotes) {
if (ch === '"') {
if (text[i + 1] === '"') { cur += '"'; i++; }
else { inQuotes = false; }
} else {
cur += ch;
}
continue;
}
if (ch === '"') { inQuotes = true; continue; }
if (ch === ',') { row.push(cur); cur = ''; continue; }
if (ch === '\r') { continue; }
if (ch === '\n') {
row.push(cur); cur = '';
cells.push(row); row = [];
continue;
}
cur += ch;
}
if (cur.length > 0 || row.length > 0) { row.push(cur); cells.push(row); }
// Drop fully-empty trailing rows so a stray newline at EOF doesn't
// produce a phantom empty record.
while (cells.length > 0 && cells[cells.length - 1].every(c => c === '')) cells.pop();
if (cells.length < 2) return [];
const header = cells[0].map(h => h.trim());
const fields = header.map(h => mapping[h] ?? h);
const out: Array<Record<string, any>> = [];
for (let r = 1; r < cells.length; r++) {
const row = cells[r];
const obj: Record<string, any> = {};
for (let c = 0; c < fields.length; c++) {
const key = fields[c];
if (!key) continue;
const raw = row[c] ?? '';
obj[key] = raw;
}
out.push(obj);
}
return out;
}
/**
* Escape a single value into an RFC-4180 CSV cell. Values containing
* commas, quotes, CR, or LF are wrapped in double-quotes with embedded
* quotes doubled. `null` / `undefined` become an empty cell. Objects and
* arrays are serialised as compact JSON so nested data round-trips
* without flattening surprises.
*/
function formatCsvCell(value: any): string {
if (value === null || value === undefined) return '';
let s: string;
if (typeof value === 'string') s = value;
else if (typeof value === 'number' || typeof value === 'boolean' || typeof value === 'bigint') s = String(value);
else if (value instanceof Date) s = value.toISOString();
else { try { s = JSON.stringify(value); } catch { s = String(value); } }
if (/[",\r\n]/.test(s)) {
return `"${s.replace(/"/g, '""')}"`;
}
return s;
}
/**
* Serialise a list of rows to RFC-4180 CSV text. Caller supplies the
* ordered list of field names; unknown fields produce empty cells.
*/
function rowsToCsv(fields: string[], rows: Array<Record<string, any>>, includeHeader: boolean): string {
const lines: string[] = [];
if (includeHeader) lines.push(fields.map(formatCsvCell).join(','));
for (const row of rows) {
lines.push(fields.map(f => formatCsvCell(row?.[f])).join(','));
}
return lines.join('\r\n') + (lines.length > 0 ? '\r\n' : '');
}
/**
* Structural subset of `KernelManager` that RestServer needs in order to
* resolve a per-project protocol at request time. Typed locally to avoid
* an @objectstack/runtime → @objectstack/rest → @objectstack/runtime
* package cycle.
*/
export interface RestKernelManager {
getOrCreate(projectId: string): Promise<{
getServiceAsync<T = unknown>(name: string): Promise<T>;
}>;
}
/**
* Normalized REST Server Configuration
* All nested properties are required after normalization
*/
type NormalizedRestServerConfig = {
api: {
version: string;
basePath: string;
apiPath: string | undefined;
enableCrud: boolean;
enableMetadata: boolean;
enableUi: boolean;
enableBatch: boolean;
enableDiscovery: boolean;
enableSearch?: boolean;
enableProjectScoping: boolean;
projectResolution: 'required' | 'optional' | 'auto';
requireAuth: boolean;
documentation: RestApiConfig['documentation'];
responseFormat: RestApiConfig['responseFormat'];
};
crud: {
operations: {
create: boolean;
read: boolean;
update: boolean;
delete: boolean;
list: boolean;
};
patterns: CrudEndpointsConfig['patterns'];
dataPrefix: string;
objectParamStyle: 'path' | 'query';
};
metadata: {
prefix: string;
enableCache: boolean;
cacheTtl: number;
endpoints: {
types: boolean;
items: boolean;
item: boolean;
schema: boolean;
};
};
batch: {
maxBatchSize: number;
enableBatchEndpoint: boolean;
operations: {
createMany: boolean;
updateMany: boolean;
deleteMany: boolean;
upsertMany: boolean;
};
defaultAtomic: boolean;
};
routes: {
includeObjects: string[] | undefined;
excludeObjects: string[] | undefined;
nameTransform: 'none' | 'plural' | 'kebab-case' | 'camelCase';
overrides: RouteGenerationConfig['overrides'];
};
};
/**
* RestServer
*
* Provides automatic REST API endpoint generation for ObjectStack.
* Generates standard RESTful CRUD endpoints, metadata endpoints, and batch operations
* based on the configured protocol provider.
*
* Features:
* - Automatic CRUD endpoint generation (GET, POST, PUT, PATCH, DELETE)
* - Metadata API endpoints (/meta)
* - Batch operation endpoints (/batch, /createMany, /updateMany, /deleteMany)
* - Discovery endpoint
* - Configurable path prefixes and patterns
*
* @example
* const restServer = new RestServer(httpServer, protocolProvider, {
* api: {
* version: 'v1',
* basePath: '/api'
* },
* crud: {
* dataPrefix: '/data'
* }
* });
*
* restServer.registerRoutes();
*/
/**
* Minimal env registry shape consumed by the REST server for hostname →
* projectId resolution and `X-Project-Id` header validation on unscoped
* routes. Mirrors the surface of `EnvironmentDriverRegistry` defined in
* `@objectstack/service-cloud`.
*/
export interface RestEnvRegistry {
resolveByHostname(hostname: string): Promise<{ projectId: string } | null | undefined>;
/**
* Look up a project by id. Returns a truthy value (typically an
* `IDataDriver`) when the project exists and is bound, `null` when
* unknown. The REST server only uses the truthiness; it does not
* touch the driver itself (the actual driver is loaded later via
* `KernelManager.getOrCreate(projectId)`).
*/
resolveById?(projectId: string): Promise<unknown | null>;
}
export class RestServer {
private protocol: ObjectStackProtocol;
private config: NormalizedRestServerConfig;
private routeManager: RouteManager;
private kernelManager?: RestKernelManager;
private envRegistry?: RestEnvRegistry;
private defaultProjectIdProvider?: () => string | undefined;
private authServiceProvider?: (projectId?: string) => Promise<any | undefined>;
private objectQLProvider?: (projectId?: string) => Promise<any | undefined>;
private emailServiceProvider?: (projectId?: string) => Promise<any | undefined>;
private sharingServiceProvider?: (projectId?: string) => Promise<any | undefined>;
private reportsServiceProvider?: (projectId?: string) => Promise<any | undefined>;
private approvalsServiceProvider?: (projectId?: string) => Promise<any | undefined>;
private sharingRulesServiceProvider?: (projectId?: string) => Promise<any | undefined>;
constructor(
server: IHttpServer,
protocol: ObjectStackProtocol,
config: RestServerConfig = {},
kernelManager?: RestKernelManager,
envRegistry?: RestEnvRegistry,
defaultProjectIdProvider?: () => string | undefined,
authServiceProvider?: (projectId?: string) => Promise<any | undefined>,
objectQLProvider?: (projectId?: string) => Promise<any | undefined>,
emailServiceProvider?: (projectId?: string) => Promise<any | undefined>,
sharingServiceProvider?: (projectId?: string) => Promise<any | undefined>,
reportsServiceProvider?: (projectId?: string) => Promise<any | undefined>,
approvalsServiceProvider?: (projectId?: string) => Promise<any | undefined>,
sharingRulesServiceProvider?: (projectId?: string) => Promise<any | undefined>,
) {
this.protocol = protocol;
this.config = this.normalizeConfig(config);
this.routeManager = new RouteManager(server);
this.kernelManager = kernelManager;
this.envRegistry = envRegistry;
this.defaultProjectIdProvider = defaultProjectIdProvider;
this.authServiceProvider = authServiceProvider;
this.objectQLProvider = objectQLProvider;
this.emailServiceProvider = emailServiceProvider;
this.sharingServiceProvider = sharingServiceProvider;
this.reportsServiceProvider = reportsServiceProvider;
this.approvalsServiceProvider = approvalsServiceProvider;
this.sharingRulesServiceProvider = sharingRulesServiceProvider;
}
/**
* Resolve the protocol for a given request. When `projectId` is present
* and a KernelManager is wired, fetch the per-project kernel's
* `protocol` service so metadata / data / UI reads hit the project's
* own registry and datastore.
*
* When `projectId` is absent on an unscoped route and an `envRegistry`
* is wired (runtime mode), the resolution chain is:
* 1. Hostname → projectId (`envRegistry.resolveByHostname`)
* 2. `X-Project-Id` header → projectId (`envRegistry.resolveById`)
* 3. Default-project fallback (`defaultProjectIdProvider`, set by
* `createSingleProjectPlugin`)
* 4. Control-plane protocol captured at boot.
*
* Special case: `projectId === 'platform'` is a reserved virtual id used
* by Studio to address the control plane through the regular project
* URL shape (`/projects/platform/...`). It is NOT a row in the projects
* table, so we must never call `KernelManager.getOrCreate('platform')`.
* Instead, return the control-plane protocol directly. This lets Studio
* (and any other client) speak a single, uniform URL family without
* duplicating route logic for the platform surface.
*/
private async resolveProtocol(projectId?: string, req?: any): Promise<ObjectStackProtocol> {
if (projectId === 'platform') return this.protocol;
if (!projectId && req && this.envRegistry && this.kernelManager) {
const host = this.extractHostname(req);
if (host) {
try {
const result = await this.envRegistry.resolveByHostname(host);
if (result?.projectId) projectId = result.projectId;
} catch {
// fall through to next strategy
}
}
// 2. `X-Project-Id` request header → projectId. Lets clients
// explicitly target a project when the URL is unscoped and
// no hostname binding exists (e.g. a single shared origin
// serving multiple compiled bundles via OS_PROJECT_ARTIFACTS).
// We validate the id through the env registry to avoid
// routing to a non-existent kernel.
if (!projectId && typeof this.envRegistry.resolveById === 'function') {
const headerVal = this.extractProjectIdHeader(req);
if (headerVal) {
try {
const driver = await this.envRegistry.resolveById(headerVal);
if (driver) projectId = headerVal;
} catch {
// fall through to default fallback
}
}
}
}
// 3. Single-project default fallback. Registered by
// `createSingleProjectPlugin()` so bare `/api/v1/data/...` URLs
// (no `/projects/<id>` prefix, no hostname mapping, no header)
// resolve to the lone project's kernel rather than the control
// plane.
if (!projectId && this.defaultProjectIdProvider) {
try {
const def = this.defaultProjectIdProvider();
if (def) projectId = def;
} catch { /* fall through */ }
}
if (!projectId || !this.kernelManager) return this.protocol;
const kernel = await this.kernelManager.getOrCreate(projectId);
return kernel.getServiceAsync<ObjectStackProtocol>('protocol');
}
/**
* Resolve the i18n service for the request's project (or control plane
* when no project id is in scope). Returns `undefined` when no service is
* registered, so callers can short-circuit and skip translation rather
* than failing.
*
* Mirrors `resolveProtocol`'s lookup chain: explicit `projectId` from the
* route → kernel-managed `i18n` service. Control-plane / unscoped
* requests intentionally return `undefined` because the platform kernel
* does not own per-app translation bundles.
*/
private async resolveI18nService(projectId?: string): Promise<any | undefined> {
if (!projectId || projectId === 'platform' || !this.kernelManager) return undefined;
try {
const kernel = await this.kernelManager.getOrCreate(projectId);
return await kernel.getServiceAsync<any>('i18n');
} catch {
return undefined;
}
}
/**
* Reject anonymous requests with HTTP 401 when `api.requireAuth` is set.
* Returns `true` if the response was sent and the caller should stop
* processing. Returns `false` to continue.
*
* The check is intentionally narrow: only `context?.userId` counts as
* "authenticated". `isSystem` flags are never set on inbound HTTP
* requests (they're internal-only), so they cannot bypass this gate.
*/
private enforceAuth(req: any, res: any, context: any): boolean {
if (!this.config.api.requireAuth) return false;
if (context?.userId) return false;
if (req?.method === 'OPTIONS') return false;
res.status(401).json({
error: 'unauthenticated',
message: 'Authentication is required to access this endpoint.',
});
return true;
}
/**
* Resolve the request's execution context (RBAC/RLS/FLS) by looking up
* the better-auth session via the project's `auth` service. Returns
* `undefined` for anonymous requests so callers can pass `context` as-is
* to the protocol layer (the SecurityPlugin treats undefined as anon).
*/
private async resolveExecCtx(projectId: string | undefined, req: any): Promise<any | undefined> {
try {
// For multi-tenant hosts (objectos), incoming requests on unscoped
// URLs like `/api/v1/data/:object` arrive with `projectId === undefined`.
// The route's protocol resolver already maps hostname → projectId
// (see resolveProtocol). We mirror that here so getSession() can
// find the right per-project auth service. Without this, the
// hostname-routed requests fall through to defaultProjectIdProvider/
// authServiceProvider (neither of which is wired in objectos) and
// every authenticated user sees 401.
if (!projectId && req && this.envRegistry && this.kernelManager) {
const host = this.extractHostname(req);
if (host) {
try {
const result = await this.envRegistry.resolveByHostname(host);
if (result?.projectId) projectId = result.projectId;
} catch { /* fall through */ }
}
if (!projectId && typeof this.envRegistry.resolveById === 'function') {
const headerVal = this.extractProjectIdHeader(req);
if (headerVal) {
try {
const driver = await this.envRegistry.resolveById(headerVal);
if (driver) projectId = headerVal;
} catch { /* fall through */ }
}
}
}
// Look up the auth service in the right kernel. For unscoped
// single-project apps the kernelManager will hand us the lone
// tenant kernel; for multi-project hosts we use the resolved
// projectId.
let authService: any;
let kernel: any;
if (projectId && projectId !== 'platform' && this.kernelManager) {
kernel = await this.kernelManager.getOrCreate(projectId);
authService = await kernel.getServiceAsync('auth').catch(() => undefined);
}
if (!authService && this.defaultProjectIdProvider && this.kernelManager) {
try {
const def = this.defaultProjectIdProvider();
if (def) {
kernel = await this.kernelManager.getOrCreate(def);
authService = await kernel.getServiceAsync('auth').catch(() => undefined);
}
} catch { /* fall through */ }
}
// Single-kernel deployment fallback — no kernelManager, but
// the plugin wired an `authServiceProvider` that hits the
// local kernel directly.
if (!authService && this.authServiceProvider) {
authService = await this.authServiceProvider(projectId).catch(() => undefined);
}
if (!authService) return undefined;
// The auth service may be the AuthManager wrapper (which exposes
// `getApi()`) or the raw better-auth instance (which exposes
// `.api` directly). Normalize to the raw API object.
let api: any = authService.api;
if (!api && typeof authService.getApi === 'function') {
api = await authService.getApi();
}
if (!api?.getSession) return undefined;
// better-auth's `getSession` requires a Web `Headers` instance
// (it calls `headers.get('cookie')`). Adapter req.headers may
// already be one, or a plain object — normalize.
const rawHeaders: any = req?.headers;
let headers: any;
if (rawHeaders && typeof rawHeaders.get === 'function') {
headers = rawHeaders;
} else if (rawHeaders && typeof rawHeaders === 'object') {
headers = new (globalThis as any).Headers();
for (const [k, v] of Object.entries(rawHeaders)) {
if (Array.isArray(v)) v.forEach((x) => headers.append(k, String(x)));
else if (v != null) headers.set(k, String(v));
}
} else {
return undefined;
}
const session = await api.getSession({ headers });
if (!session?.user?.id) return undefined;
const userId = session.user.id;
const tenantId = session.session?.activeOrganizationId ?? undefined;
const permissions: string[] = [];
const roles: string[] = [];
// Look up the link tables to surface roles + permission set names.
// Skipping this lookup would silently ignore admin/role grants —
// including the platform-admin promotion seeded by
// `bootstrapPlatformAdmin` — and force every authenticated user
// through the `member_default` fallback path.
try {
let ql: any;
if (kernel) {
ql = await kernel.getServiceAsync('objectql').catch(() => undefined);
}
if (!ql && this.objectQLProvider) {
ql = await this.objectQLProvider(projectId).catch(() => undefined);
}
if (ql && typeof ql.find === 'function') {
const sysOpts = { context: { isSystem: true } };
const memberRows = await ql.find('sys_member', {
where: tenantId ? { user_id: userId, organization_id: tenantId } : { user_id: userId },
limit: 50,
...sysOpts,
} as any).catch(() => []);
for (const m of (memberRows ?? []) as any[]) {
if (typeof m.role === 'string') {
for (const r of m.role.split(',').map((s: string) => s.trim()).filter(Boolean)) {
if (!roles.includes(r)) roles.push(r);
}
}
}
const upsRows = await ql.find('sys_user_permission_set', {
where: { user_id: userId },
limit: 100,
...sysOpts,
} as any).catch(() => []);
const psIds = new Set<string>();
for (const r of (upsRows ?? []) as any[]) {
const orgScope = r.organization_id ?? null;
if (!orgScope || (tenantId && orgScope === tenantId)) {
const pid = r.permission_set_id ?? r.permissionSetId;
if (pid) psIds.add(pid);
}
}
if (psIds.size > 0) {
const psRows = await ql.find('sys_permission_set', {
where: { id: { $in: Array.from(psIds) } },
limit: 500,
...sysOpts,
} as any).catch(() => []);
for (const ps of (psRows ?? []) as any[]) {
if (ps.name && !permissions.includes(ps.name)) permissions.push(ps.name);
}
}
}
} catch { /* fall through with empty perms */ }
return {
userId,
tenantId,
roles,
permissions,
isSystem: false,
};
} catch {
return undefined;
}
}
/**
* Build a `TranslationBundle` (`Record<locale, TranslationData>`) from an
* `II18nService` instance. Returns `undefined` when no locales are
* registered so callers can avoid translation work.
*/
private buildTranslationBundle(i18n: any): any | undefined {
if (!i18n || typeof i18n.getLocales !== 'function' || typeof i18n.getTranslations !== 'function') {
return undefined;
}
const locales: string[] = i18n.getLocales();
if (!locales.length) return undefined;
const bundle: Record<string, any> = {};
for (const locale of locales) {
const data = i18n.getTranslations(locale);
if (data && typeof data === 'object') bundle[locale] = data;
}
return Object.keys(bundle).length ? bundle : undefined;
}
/**
* Parse the highest-priority locale from an `Accept-Language` header.
* Falls back to a `?locale=` query parameter, then to the i18n service's
* default locale. Returns `undefined` when no preference is expressed
* (callers will then return untranslated metadata).
*/
private extractLocale(req: any, i18n?: any): string | undefined {
const headers = req?.headers;
let header: string | undefined;
if (headers) {
header = typeof headers.get === 'function'
? headers.get('accept-language') ?? undefined
: headers['accept-language'] ?? headers['Accept-Language'];
}
if (typeof header === 'string' && header.length > 0) {
const top = header.split(',')[0]?.split(';')[0]?.trim();
if (top) return top;
}
const queryLocale = req?.query?.locale;
if (typeof queryLocale === 'string' && queryLocale.length > 0) return queryLocale;
if (i18n && typeof i18n.getDefaultLocale === 'function') {
const def = i18n.getDefaultLocale();
if (typeof def === 'string' && def.length > 0) return def;
}
return undefined;
}
/**
* Translate a single metadata document (view or action) when an i18n
* service is registered for the request's project and the requested
* locale yields a match. Falls through unchanged for unsupported types
* or missing translations.
*/
private async translateMetaItem(req: any, type: string, projectId: string | undefined, item: any): Promise<any> {
if (!item || typeof item !== 'object') return item;
if (type !== 'view' && type !== 'action') return item;
const i18n = await this.resolveI18nService(projectId);
const bundle = this.buildTranslationBundle(i18n);
if (!bundle) return item;
const locale = this.extractLocale(req, i18n);
if (!locale) return item;
const { translateMetadataDocument } = await import('@objectstack/spec/system');
return translateMetadataDocument(type, item, bundle, { locale });
}
/**
* Translate a list of metadata documents using `translateMetaItem`.
*/
private async translateMetaItems(req: any, type: string, projectId: string | undefined, items: any): Promise<any> {
if (!Array.isArray(items)) return items;
if (type !== 'view' && type !== 'action') return items;
const i18n = await this.resolveI18nService(projectId);
const bundle = this.buildTranslationBundle(i18n);
if (!bundle) return items;
const locale = this.extractLocale(req, i18n);
if (!locale) return items;
const { translateMetadataDocument } = await import('@objectstack/spec/system');
return items.map((item) => translateMetadataDocument(type, item, bundle, { locale }));
}
/**
* Pull the request hostname (without port) from a Node-style `req` or
* a Fetch-style request wrapper. Returns undefined when no Host header
* is available.
*/
private extractHostname(req: any): string | undefined {
const headers = req?.headers;
let host: string | undefined;
if (headers) {
if (typeof headers.get === 'function') {
host = headers.get('host') ?? undefined;
} else {
host = headers.host ?? headers.Host;
}
}
if (!host && typeof req?.hostname === 'string') host = req.hostname;
if (!host && typeof req?.url === 'string') {
// Fetch-style requests expose the hostname via `req.url` even
// when the (forbidden) `Host` header has been stripped by the
// runtime. This branch keeps hostname-routing working when
// tests build a `Request` object through `app.fetch(...)`.
try {
host = new (globalThis as any).URL(req.url).host;
} catch { /* ignore */ }
}
if (!host) return undefined;
return String(host).split(':')[0].toLowerCase();
}
/**
* Pull the `X-Project-Id` header from a Node- or Fetch-style request.
* Header names are case-insensitive; we probe both casings to cover
* adapters that don't normalize headers (e.g. raw Node http).
*/
private extractProjectIdHeader(req: any): string | undefined {
const headers = req?.headers;
if (!headers) return undefined;
let val: unknown;
if (typeof headers.get === 'function') {
val = headers.get('x-project-id') ?? headers.get('X-Project-Id');
} else {
val = headers['x-project-id'] ?? headers['X-Project-Id'];
}
if (Array.isArray(val)) val = val[0];
if (typeof val !== 'string') return undefined;
const trimmed = val.trim();
return trimmed.length > 0 ? trimmed : undefined;
}
/**
* Normalize configuration with defaults
*/
private normalizeConfig(config: RestServerConfig): NormalizedRestServerConfig {
const api = (config.api ?? {}) as Partial<RestApiConfig>;
const crud = (config.crud ?? {}) as Partial<CrudEndpointsConfig>;
const metadata = (config.metadata ?? {}) as Partial<MetadataEndpointsConfig>;
const batch = (config.batch ?? {}) as Partial<BatchEndpointsConfig>;
const routes = (config.routes ?? {}) as Partial<RouteGenerationConfig>;
return {
api: {
version: api.version ?? 'v1',
basePath: api.basePath ?? '/api',
apiPath: api.apiPath,
enableCrud: api.enableCrud ?? true,
enableMetadata: api.enableMetadata ?? true,
enableUi: api.enableUi ?? true,
enableBatch: api.enableBatch ?? true,
enableDiscovery: api.enableDiscovery ?? true,
enableSearch: (api as any).enableSearch ?? true,
enableProjectScoping: api.enableProjectScoping ?? false,
projectResolution: api.projectResolution ?? 'auto',
requireAuth: (api as any).requireAuth ?? false,
documentation: api.documentation,
responseFormat: api.responseFormat,
},
crud: {
operations: crud.operations ?? {
create: true,
read: true,
update: true,
delete: true,
list: true,
},
patterns: crud.patterns,
dataPrefix: crud.dataPrefix ?? '/data',
objectParamStyle: crud.objectParamStyle ?? 'path',
},
metadata: {
prefix: metadata.prefix ?? '/meta',
enableCache: metadata.enableCache ?? true,
cacheTtl: metadata.cacheTtl ?? 3600,
endpoints: metadata.endpoints ?? {
types: true,
items: true,
item: true,
schema: true,
},
},
batch: {
maxBatchSize: batch.maxBatchSize ?? 200,
enableBatchEndpoint: batch.enableBatchEndpoint ?? true,
operations: batch.operations ?? {
createMany: true,
updateMany: true,
deleteMany: true,
upsertMany: true,
},
defaultAtomic: batch.defaultAtomic ?? true,
},
routes: {
includeObjects: routes.includeObjects,
excludeObjects: routes.excludeObjects,
nameTransform: routes.nameTransform ?? 'none',
overrides: routes.overrides,
},
};
}
/**
* Get the full API base path
*/
private getApiBasePath(): string {
const { api } = this.config;
return api.apiPath ?? `${api.basePath}/${api.version}`;
}
/**
* Get the project-scoped base path for a given unscoped base.
* Example: `/api/v1` → `/api/v1/projects/:projectId`.
*/
private getScopedBasePath(basePath: string): string {
return `${basePath}/projects/:projectId`;
}
/**
* Register all REST API routes
*
* When `enableProjectScoping` is true, routes are registered under
* `/api/v1/projects/:projectId/...`. The `projectResolution` strategy
* controls whether unscoped legacy routes remain available:
* - `required` → only scoped routes registered.
* - `optional` / `auto` → both scoped and unscoped routes registered.
*/
registerRoutes(): void {
const basePath = this.getApiBasePath();
const { enableProjectScoping, projectResolution } = this.config.api;
const registerForBase = (bp: string) => {
if (this.config.api.enableDiscovery) {
this.registerDiscoveryEndpoints(bp);
}
if (this.config.api.enableMetadata) {
this.registerMetadataEndpoints(bp);
}
if (this.config.api.enableUi) {
this.registerUiEndpoints(bp);
}
if (this.config.api.enableSearch ?? true) {
this.registerSearchEndpoints(bp);
}
this.registerEmailEndpoints(bp);
// Public (anonymous) form endpoints — opt-in via FormView.sharing.
// Registered BEFORE the greedy `/data/:object` matcher so the
// `/forms/:slug` and `/forms/:slug/submit` paths can't be
// shadowed by a literal object named "forms".
this.registerFormEndpoints(bp);
// Capability routes (sharing rules, reports, approvals) live at
// the top of the API surface (`/api/v1/{capability}/...`) rather
// than under `/data/`, so they don't collide with the greedy
// CRUD `/:object` matcher and don't pretend to be records on a
// single object.
this.registerSharingEndpoints(bp);
this.registerSharingRuleEndpoints(bp);
this.registerReportsEndpoints(bp);
this.registerApprovalsEndpoints(bp);
if (this.config.api.enableCrud) {
this.registerCrudEndpoints(bp);
}
this.registerDataActionEndpoints(bp);
if (this.config.api.enableBatch) {
this.registerBatchEndpoints(bp);
}
};
if (enableProjectScoping) {
const scopedBase = this.getScopedBasePath(basePath);
if (projectResolution === 'required') {
// Strict: only scoped routes
registerForBase(scopedBase);
} else {
// 'optional' | 'auto' — keep both so legacy callers keep working
registerForBase(basePath);
registerForBase(scopedBase);
}
} else {
registerForBase(basePath);
}
}
/**
* Register discovery endpoints
*/