-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathhono-plugin.ts
More file actions
1295 lines (1223 loc) · 65.2 KB
/
Copy pathhono-plugin.ts
File metadata and controls
1295 lines (1223 loc) · 65.2 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 {
Plugin, PluginContext, IDataEngine,
shouldDenyAnonymous, ANONYMOUS_DENY_BODY, ANONYMOUS_DENY_STATUS,
derivePosture,
} from '@objectstack/core';
import {
RestServerConfig,
} from '@objectstack/spec/api';
import { ADMIN_FULL_ACCESS, ORGANIZATION_ADMIN } from '@objectstack/spec';
import type { ExecutionContext } from '@objectstack/spec/kernel';
import { HonoHttpServer, HonoCorsOptions } from './adapter';
import { cors } from 'hono/cors';
import { serveStatic } from '@hono/node-server/serve-static';
import * as fs from 'fs';
import * as path from 'path';
import { createOriginMatcher, hasWildcardPattern, isLocalhostOrigin } from './pattern-matcher';
import { readEnvWithDeprecation } from '@objectstack/types';
import {
PerfTiming,
runWithPerfTiming,
runWithPerfDisclosure,
allowPerfDisclosure,
isPerfDisclosurePrincipal,
type PerfDisclosureGate,
} from '@objectstack/observability';
export interface StaticMount {
root: string;
path?: string;
rewrite?: boolean;
spa?: boolean;
}
export interface HonoPluginOptions {
port?: number;
staticRoot?: string;
/**
* Multiple static resource mounts
*/
staticMounts?: StaticMount[];
/**
* REST server configuration
* Controls automatic endpoint generation and API behavior
*/
restConfig?: RestServerConfig;
/**
* Whether to register standard ObjectStack CRUD endpoints
* @default true
*/
registerStandardEndpoints?: boolean;
/**
* Whether to load endpoints from API Registry
* @default true
*/
useApiRegistry?: boolean;
/**
* Whether to enable SPA fallback
* If true, returns index.html for non-API 404s
* @default false
*/
spaFallback?: boolean;
/**
* CORS configuration. Set to `false` to disable entirely.
* Enabled by default with origin '*'.
* Can also be controlled via environment variables:
* OS_CORS_ENABLED, OS_CORS_ORIGIN, OS_CORS_CREDENTIALS, OS_CORS_MAX_AGE
* (legacy CORS_* names still honoured with a deprecation warning).
*/
cors?: HonoCorsOptions | false;
/**
* Per-request performance timing via the `Server-Timing` response header
* ("perf-tuning mode"). The header discloses internal phase durations
* (total / auth / db / hooks / serialize), which is handy for profiling but
* is also a mild backend-fingerprinting surface, so disclosure is gated:
*
* - **GLOBAL** — `serverTiming: true`, or `OS_SERVER_TIMING=true` /
* `OS_PERF_TIMING=1`: every response carries the header (an environment
* under active investigation).
* - **PER-REQUEST** — always available unless hard-disabled: a caller sends
* `X-OS-Debug-Timing: 1` and the header is returned ONLY after the request
* resolves an admin/service identity (the dispatcher opens the disclosure
* gate). Ordinary users can never pull timings just by sending the header.
* `X-OS-Debug-Timing: json` additionally returns an admin-only
* `X-OS-Debug-Timing-Detail` header — compact JSON listing the slowest
* per-query SQL *shapes* (parametrized, no bindings) — never disclosed to
* a non-admin, even under global mode.
* - `serverTiming: false` hard-disables BOTH paths (no middleware).
*
* `undefined` (the default) leaves global mode off but keeps the
* admin-gated per-request path available.
* @default undefined
*/
serverTiming?: boolean;
}
/**
* Hono Server Plugin
*
* Provides HTTP server capabilities using Hono framework.
* Registers the IHttpServer service so other plugins can register routes.
*
* Route registration is handled by plugins:
* - `@objectstack/rest` → CRUD, metadata, discovery, UI, batch
* - `createDispatcherPlugin()` → auth, graphql, analytics, packages, etc.
*/
/**
* Fold the `'*'` wildcard super-user grant into every per-object entry of a
* `/me/permissions` `objects` map, mutating it in place.
*
* The endpoint merges each resolved permission set's explicit `objects` entries
* most-permissively per key, but treats `'*'` and named objects as independent
* keys — so a wildcard "Modify/View All Data" grant is never propagated into a
* per-object entry another set explicitly denied. That makes the client's
* per-object FLS STRICTER than the server's actual enforcement
* (`PermissionEvaluator.checkObjectPermission`, which returns allow as soon as
* ANY set grants — including via the `'*'` modifyAll/viewAll super-user bypass,
* with no deny-wins). The mismatch surfaces for a platform admin
* (`admin_full_access` `'*': {modifyAllRecords}`) who ALSO holds
* `organization_admin` (which denies writes on identity tables): the client
* would see `sys_user.allowEdit:false` and disable a form the server accepts
* (verified: `PATCH /data/sys_user {name}` → 200). ADR-0057 D10 makes the
* server the authoritative gate; the client must mirror it, never diverge.
*
* The super-user grant covers private/managed objects on the server, so folding
* it here is exactly as broad as real enforcement — never broader.
*/
export function foldWildcardSuperUser(objects: Record<string, any>): void {
const wild = objects?.['*'];
if (!wild) return;
const superRead = wild.viewAllRecords === true || wild.modifyAllRecords === true;
const superWrite = wild.modifyAllRecords === true;
if (!superRead && !superWrite) return;
for (const [obj, acc] of Object.entries(objects) as Array<[string, any]>) {
if (obj === '*' || !acc) continue;
if (superRead) acc.allowRead = true;
if (superWrite) {
acc.allowEdit = true;
acc.allowCreate = true;
acc.allowDelete = true;
}
}
}
/**
* How much per-request timing the caller opted into via `X-OS-Debug-Timing`:
* - `off` — no header sent (or an unrecognized value).
* - `basic` — `1` / `true` / `yes` / `on`: the `Server-Timing` header only.
* - `json` — `json` / `detail` / `verbose`: also the admin-only richer detail
* payload (per-query SQL shapes, slowest query).
*/
export type DebugTimingMode = 'off' | 'basic' | 'json';
/** Parse the `X-OS-Debug-Timing` request-header value into a {@link DebugTimingMode}. */
export function debugTimingMode(value: string | undefined | null): DebugTimingMode {
if (!value) return 'off';
const v = value.trim().toLowerCase();
if (v === 'json' || v === 'detail' || v === 'verbose') return 'json';
if (v === '1' || v === 'true' || v === 'yes' || v === 'on') return 'basic';
return 'off';
}
/**
* Whether a request opted into per-request perf timing via `X-OS-Debug-Timing`
* (any recognized mode — basic or json).
*/
export function isDebugTimingRequested(value: string | undefined | null): boolean {
return debugTimingMode(value) !== 'off';
}
/** Max individual queries listed in the detail payload (bounds header size). */
const DETAIL_MAX_QUERIES = 20;
/** Max characters kept per query label in the detail payload. */
const DETAIL_MAX_LABEL = 300;
/**
* Coerce a detail label (a parametrized SQL statement) to a header-safe,
* printable-ASCII string: non-token bytes and control chars become spaces so the
* JSON stays valid and the `X-OS-Debug-Timing-Detail` header can never carry a
* CR/LF (header-injection) or a non-latin1 byte the Fetch Headers API rejects.
*/
function sanitizeDetailLabel(s: string): string {
let out = '';
for (const ch of String(s)) {
const c = ch.codePointAt(0)!;
out += c >= 0x20 && c <= 0x7e ? ch : ' ';
}
return out.replace(/\s+/g, ' ').trim().slice(0, DETAIL_MAX_LABEL);
}
/**
* Build the admin-only `X-OS-Debug-Timing-Detail` payload (compact JSON) from a
* collector's captured `db` detail: the slowest queries by shape, the single
* slowest, and the captured count + total. Returns `''` when nothing was
* captured. SQL is parametrized (no bindings) and sanitized to printable ASCII.
*/
export function buildTimingDetail(timing: PerfTiming): string {
const db = timing.details('db');
if (db.length === 0) return '';
const round = (n: number) => Math.round(n * 100) / 100;
const sorted = [...db].sort((a, b) => b.dur - a.dur);
const queries = sorted.slice(0, DETAIL_MAX_QUERIES).map((d) => ({
sql: sanitizeDetailLabel(d.label),
dur: round(d.dur),
}));
const totalMs = round(db.reduce((sum, d) => sum + d.dur, 0));
const payload: Record<string, unknown> = {
db: {
count: db.length,
totalMs,
slowest: queries[0] ?? null,
queries,
...(sorted.length > queries.length ? { truncated: sorted.length - queries.length } : {}),
},
};
return JSON.stringify(payload);
}
/** Minimal schema shape the managed-write clamp needs. */
export interface ManagedSchemaLike {
managedBy?: string;
userActions?: {
create?: boolean;
// edit/delete accept the #2614 object form ({ enabled, visibleWhen,
// disabledWhen }); only the object-level `enabled` matters here — the
// per-record predicates are UI gating, not a permission grant.
edit?: boolean | { enabled?: boolean };
delete?: boolean | { enabled?: boolean };
} | null;
}
/** True only when a userActions flag (bare boolean or object form) explicitly opts the write in. */
function isWriteOptedIn(v: boolean | { enabled?: boolean } | undefined | null): boolean {
return v === true || (typeof v === 'object' && v !== null && v.enabled === true);
}
/**
* Buckets whose user-context generic writes are guarded fail-closed at the
* engine: `better-auth` by plugin-auth's identity write guard (ADR-0092 D2),
* `engine-owned` / `system` / `append-only` by plugin-security's engine-owned
* write guard (ADR-0103). `config` / `platform` have no such guard — their
* permission-set result stands.
*/
const GUARDED_WRITE_BUCKETS: ReadonlySet<string> = new Set(['better-auth', 'system', 'engine-owned', 'append-only']);
/**
* Re-clamp a `/me/permissions` `objects` map by the SECOND server-side
* enforcement layer that permission sets don't model: the engine write guards.
* They fail-closed reject USER-CONTEXT insert/update/delete on every managed
* object whose resolved affordances forbid the verb — `better-auth`
* (ADR-0092 D2) and `system`/`append-only` (ADR-0103) — except where the object
* opted the write affordance in via `userActions.{create,edit,delete}` (e.g.
* sys_user opens `edit` for its profile fields; the RBAC link tables / prefs /
* messaging config open their CRUD).
*
* Without this clamp, {@link foldWildcardSuperUser} would report `allowEdit:true`
* for a platform admin on tables the guard actually blocks (sys_member,
* sys_automation_run, …) — a false-POSITIVE that mirrors, inverted, the
* false-negative the fold fixes. The real effective answer for a user-context
* caller is `permission-set grant ∩ guard policy`, and the guard policy for a
* guarded object is exactly its resolved CRUD affordance. `config`/`platform`
* objects are NOT clamped — no guard covers them, so their permission-set result
* stands (an admin CAN write them via the data API, and the hint must not
* under-report that).
*/
export function clampManagedObjectWrites(
objects: Record<string, any>,
schemaOf: (objectName: string) => ManagedSchemaLike | undefined,
): void {
for (const [obj, acc] of Object.entries(objects) as Array<[string, any]>) {
if (obj === '*' || !acc) continue;
const schema = schemaOf(obj);
if (!schema?.managedBy || !GUARDED_WRITE_BUCKETS.has(schema.managedBy)) continue;
const ua = schema.userActions ?? {};
if (!isWriteOptedIn(ua.edit)) acc.allowEdit = false;
if (ua.create !== true) acc.allowCreate = false;
if (!isWriteOptedIn(ua.delete)) acc.allowDelete = false;
}
}
export class HonoServerPlugin implements Plugin {
name = 'com.objectstack.server.hono';
type = 'server';
version = '0.9.0';
// Constants
private static readonly DEFAULT_ENDPOINT_PRIORITY = 100;
private static readonly CORE_ENDPOINT_PRIORITY = 950;
private static readonly DISCOVERY_ENDPOINT_PRIORITY = 900;
private options: HonoPluginOptions;
private server: HonoHttpServer;
constructor(options: HonoPluginOptions = {}) {
this.options = {
port: 3000,
registerStandardEndpoints: true,
useApiRegistry: true,
spaFallback: false,
...options
};
// We handle static root manually in start() to support SPA fallback
this.server = new HonoHttpServer(this.options.port);
}
/**
* Init phase - Setup HTTP server and register as service
*/
init = async (ctx: PluginContext) => {
ctx.logger.debug('Initializing Hono server plugin', {
port: this.options.port,
staticRoot: this.options.staticRoot
});
// Register HTTP server service as IHttpServer
// Register as 'http.server' to match core requirements
ctx.registerService('http.server', this.server);
// Alias 'http-server' for backward compatibility
ctx.registerService('http-server', this.server);
ctx.logger.debug('HTTP server service registered', { serviceName: 'http.server' });
// ─── Server-Timing (perf-tuning mode) ─────────────────────────────────
// Per-request performance timing exposed via the `Server-Timing`
// response header. Registered FIRST (before CORS) so the `total` mark
// brackets the whole request and the ambient timing collector is
// established — via AsyncLocalStorage — for every downstream layer
// (CORS, route handler, body parse, SQL driver, hooks) to record
// sub-phases into.
//
// Two ways to turn it on (see the `serverTiming` option JSDoc):
// • GLOBAL — `serverTiming: true` / `OS_SERVER_TIMING=true` /
// `OS_PERF_TIMING=1`: the header is returned to EVERY
// caller. The disclosure gate opens up front.
// • PER-REQUEST — the caller sends `X-OS-Debug-Timing: 1`; the header
// is returned ONLY after the dispatcher resolves an
// admin/service identity and opens the gate, so an
// ordinary user can never fingerprint the backend by
// sending the header alone.
// `serverTiming: false` hard-disables both paths (no middleware).
if (this.options.serverTiming !== false) {
const globalTiming =
this.options.serverTiming === true ||
process.env.OS_SERVER_TIMING === 'true' ||
process.env.OS_PERF_TIMING === '1' ||
process.env.OS_PERF_TIMING === 'true';
const rawApp = this.server.getRawApp();
rawApp.use('*', async (c, next) => {
const mode = debugTimingMode(c.req.header('X-OS-Debug-Timing'));
// Nothing asked for timing on this request — a single header
// read, then straight through. Zero collector overhead.
if (!globalTiming && mode === 'off') return next();
const timing = new PerfTiming();
// `json` opts into per-query DETAIL capture (parametrized SQL
// shapes) — recorded now, disclosed later only to an admin.
if (mode === 'json') timing.enableDetail();
// Global mode opens the gate for everyone; the per-request path
// starts closed and is opened only if an admin/service identity
// is proven during dispatch (`allowPerfDisclosure`).
const gate: PerfDisclosureGate = { allowed: globalTiming };
const endTotal = timing.start('total', 'Total server time');
await runWithPerfTiming(timing, () => runWithPerfDisclosure(gate, () => next()));
endTotal();
if (!gate.allowed) return; // per-request, unverified caller — withhold
const header = timing.toHeader();
// `append` (not `set`) so we coexist with any upstream proxy
// that already added a Server-Timing entry.
if (header) c.res.headers.append('Server-Timing', header);
// Richer per-query detail is ADMIN-ONLY — even under global mode
// an ordinary caller must never see SQL shapes. Emit only when the
// principal was proven privileged (admin/service) AND detail was
// requested/captured.
if (gate.privileged && timing.detailEnabled) {
const detail = buildTimingDetail(timing);
// Guard the append: an exotic label the Fetch Headers API
// still rejects must never break the response.
if (detail) {
try {
c.res.headers.append('X-OS-Debug-Timing-Detail', detail);
} catch {
/* header rejected — skip the detail, keep the response */
}
}
}
});
ctx.logger.debug('Server-Timing (perf-tuning) middleware enabled');
}
// ─── CORS Middleware ──────────────────────────────────────────────────
// Enabled by default. Controlled via options.cors or environment variables.
const corsDisabledByEnv = readEnvWithDeprecation('OS_CORS_ENABLED', 'CORS_ENABLED', { silent: true }) === 'false';
if (this.options.cors !== false && !corsDisabledByEnv) {
const corsOpts = typeof this.options.cors === 'object' ? this.options.cors : {};
const enabled = corsOpts.enabled ?? true;
if (enabled) {
let configuredOrigin: string | string[];
const corsOriginEnv = readEnvWithDeprecation('OS_CORS_ORIGIN', 'CORS_ORIGIN', { silent: true });
if (corsOpts.origins) {
configuredOrigin = corsOpts.origins;
} else if (corsOriginEnv) {
const envOrigin = corsOriginEnv.trim();
configuredOrigin = envOrigin.includes(',') ? envOrigin.split(',').map(s => s.trim()) : envOrigin;
} else {
configuredOrigin = '*';
}
const credentials = corsOpts.credentials ?? (readEnvWithDeprecation('OS_CORS_CREDENTIALS', 'CORS_CREDENTIALS', { silent: true }) !== 'false');
const maxAgeEnv = readEnvWithDeprecation('OS_CORS_MAX_AGE', 'CORS_MAX_AGE', { silent: true });
const maxAge = corsOpts.maxAge ?? (maxAgeEnv ? parseInt(maxAgeEnv, 10) : 86400);
// Determine origin handler based on configuration.
// Always use a function so that localhost origins are
// automatically allowed regardless of the configured
// pattern list (handled inside matchOriginPattern /
// createOriginMatcher).
let origin: string | string[] | ((origin: string) => string | undefined | null);
// When credentials is true, browsers reject wildcard '*' for Access-Control-Allow-Origin.
// For wildcard patterns (like "https://*.example.com"), always use a matcher function.
// For exact origins, we can pass them directly as string/array.
if (configuredOrigin === '*' && credentials) {
// Credentials mode with '*' - reflect the request origin
origin = (requestOrigin: string) => requestOrigin || '*';
} else if (hasWildcardPattern(configuredOrigin)) {
// Wildcard patterns (including better-auth style patterns like "https://*.objectui.org")
// Use pattern matcher to support subdomain and port wildcards
origin = createOriginMatcher(configuredOrigin);
} else {
// Exact origin(s) — wrap in a function so localhost is
// still auto-allowed via the matcher.
const matcher = createOriginMatcher(configuredOrigin);
origin = (requestOrigin: string) => matcher(requestOrigin);
}
const rawApp = this.server.getRawApp();
// Always include `set-auth-token` in exposed headers so that
// the better-auth `bearer()` plugin can deliver rotated
// session tokens to cross-origin clients (see plugin-auth).
// User-supplied exposeHeaders are merged with this default.
// `If-Match` carries the OCC token on record PATCHes (objectui's
// record-level inline edit, REST `update` with `ifMatch`) — without
// it in the preflight allow-list, every cross-origin save fails in
// the browser with "Failed to fetch" (objectui#2572 dogfood find;
// same split-origin class as the #2548 Bearer fixes).
const defaultAllowHeaders = ['Content-Type', 'Authorization', 'X-Requested-With', 'X-Tenant-ID', 'X-Environment-Id', 'If-Match'];
const defaultExposeHeaders = ['set-auth-token'];
const allowHeaders = corsOpts.allowHeaders ?? defaultAllowHeaders;
const exposeHeaders = Array.from(new Set([
...defaultExposeHeaders,
...(corsOpts.exposeHeaders ?? []),
]));
rawApp.use('*', cors({
origin: origin as any,
allowMethods: corsOpts.methods || ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS'],
allowHeaders,
exposeHeaders,
credentials,
maxAge,
}));
ctx.logger.debug('CORS middleware enabled', { origin: configuredOrigin, credentials });
}
}
}
/**
* Start phase - Configure static files and start listening
*/
start = async (ctx: PluginContext) => {
ctx.logger.debug('Starting Hono server plugin');
// Configure Static Files & SPA Fallback
const mounts: StaticMount[] = this.options.staticMounts || [];
// Auto-discover UI Plugins
try {
const rawKernel = ctx.getKernel() as any;
if (rawKernel.plugins) {
const loadedPlugins = rawKernel.plugins instanceof Map
? Array.from(rawKernel.plugins.values())
: Array.isArray(rawKernel.plugins) ? rawKernel.plugins : Object.values(rawKernel.plugins);
for (const plugin of (loadedPlugins as any[])) {
// Check for UI Plugin signature
// Support legacy 'ui-plugin' and new 'ui' type
if ((plugin.type === 'ui' || plugin.type === 'ui-plugin') && plugin.staticPath) {
// Derive base route from name: @org/console -> console
const slug = plugin.slug || plugin.name.split('/').pop();
const baseRoute = `/${slug}`;
ctx.logger.debug(`Auto-mounting UI Plugin: ${plugin.name}`, {
path: baseRoute,
root: plugin.staticPath
});
mounts.push({
root: plugin.staticPath,
path: baseRoute,
rewrite: true, // Strip prefix: /console/assets/x -> /assets/x
spa: true
});
// Handle Default Plugin Redirect
if (plugin.default || plugin.isDefault) {
const rawApp = this.server.getRawApp();
rawApp.get('/', (c) => c.redirect(baseRoute));
ctx.logger.debug(`Set default UI redirect: / -> ${baseRoute}`);
}
}
}
}
} catch (err: any) {
ctx.logger.warn('Failed to auto-discover UI plugins', { error: err.message || err });
}
// Backward compatibility for staticRoot
if (this.options.staticRoot) {
mounts.push({
root: this.options.staticRoot,
path: '/',
rewrite: false,
spa: this.options.spaFallback
});
}
if (mounts.length > 0) {
const rawApp = this.server.getRawApp();
for (const mount of mounts) {
const mountRoot = path.resolve(process.cwd(), mount.root);
if (!fs.existsSync(mountRoot)) {
ctx.logger.warn(`Static mount root not found: ${mountRoot}. Skipping.`);
continue;
}
const mountPath = mount.path || '/';
const normalizedPath = mountPath.startsWith('/') ? mountPath : `/${mountPath}`;
const routePattern = normalizedPath === '/' ? '/*' : `${normalizedPath.replace(/\/$/, '')}/*`;
// Routes to register: both /mount and /mount/*
const routes = normalizedPath === '/' ? [routePattern] : [normalizedPath, routePattern];
ctx.logger.debug('Mounting static files', {
to: routes,
from: mountRoot,
rewrite: mount.rewrite,
spa: mount.spa
});
routes.forEach(route => {
// 1. Serve Static Files
rawApp.get(
route,
serveStatic({
root: mount.root,
rewriteRequestPath: (reqPath) => {
if (mount.rewrite && normalizedPath !== '/') {
// /console/assets/style.css -> /assets/style.css
if (reqPath.startsWith(normalizedPath)) {
return reqPath.substring(normalizedPath.length) || '/';
}
}
return reqPath;
}
})
);
// 2. SPA Fallback (Scoped)
if (mount.spa) {
rawApp.get(route, async (c, next) => {
// Skip if API path check
const config = this.options.restConfig || {};
const basePath = config.api?.basePath || '/api';
if (c.req.path.startsWith(basePath)) {
return next();
}
return serveStatic({
root: mount.root,
rewriteRequestPath: () => 'index.html'
})(c, next);
});
}
});
}
}
// Catch-all: ensure unmatched requests always get a proper Response
// (prevents Hono "Context is not finalized" error).
//
// Hono routes a method mismatch to the SAME `notFound` sink as a
// genuinely missing path, so a `POST` to a `PUT`-only route (e.g. the
// metadata save endpoint, see #2684) used to return an opaque
// `{ error: 'Not found' }` 404 with no hint that the path exists under
// another verb. Here we re-match the request path against the set of
// registered route patterns: if it lines up with routes under other
// methods, answer `405 Method Not Allowed` with an accurate `Allow`
// header so callers can self-correct. A path that matches nothing
// stays a 404. This is framework-wide — every registered endpoint
// benefits, not just metadata.
const rawAppForNotFound = this.server.getRawApp();
if (typeof rawAppForNotFound.notFound === 'function') {
rawAppForNotFound.notFound((c: any) => {
const allowed = this.server.allowedMethodsForPath(c.req.path);
if (allowed.length > 0 && !allowed.includes(c.req.method)) {
c.header('Allow', allowed.join(', '));
return c.json({
error: 'Method Not Allowed',
code: 'METHOD_NOT_ALLOWED',
message: `${c.req.method} is not supported for ${c.req.path}. Allowed: ${allowed.join(', ')}.`,
method: c.req.method,
path: c.req.path,
allowed,
}, 405);
}
return c.json({ error: 'Not found' }, 404);
});
}
// Register standard endpoints during kernel:ready so they're
// wired up alongside other plugins' route registrations.
if (this.options.registerStandardEndpoints) {
ctx.hook('kernel:ready', async () => {
this.registerDiscoveryAndCrudEndpoints(ctx);
});
}
// Open the listening socket on kernel:listening — this fires
// STRICTLY AFTER every kernel:ready handler completes, so all
// plugins have finished registering routes by the time the
// server starts accepting requests.
//
// Why this matters: Hono seals the route matcher the first
// time a request is matched. If we listen during kernel:ready
// and a request arrives before sibling plugins (auth, i18n,
// storage, …) finish registering their routes, those late
// `app.get(...)` calls throw "matcher is already built" and
// crash the process. Cloudflare Containers fronts traffic the
// millisecond port 4000 opens, so the race fires on every
// cold boot in production. See
// packages/spec/src/contracts/plugin-lifecycle-events.ts for
// the full rationale.
ctx.hook('kernel:listening', async () => {
const port = this.options.port ?? 3000;
ctx.logger.debug('Starting HTTP server', { port });
await this.server.listen(port);
const actualPort = this.server.getPort();
if (actualPort !== port) {
ctx.logger.warn(`Port ${port} is in use, using port ${actualPort} instead`);
}
ctx.logger.info('HTTP server started successfully', {
port: actualPort,
url: `http://localhost:${actualPort}`
});
});
}
/**
* Register discovery and basic CRUD endpoints.
* Called when `registerStandardEndpoints` is true, before the server starts listening.
*/
private registerDiscoveryAndCrudEndpoints(ctx: PluginContext) {
const rawApp = this.server.getRawApp();
const prefix = '/api/v1';
// Build the standard discovery response
const discovery = {
version: 'v1',
apiName: 'ObjectStack API',
routes: {
data: `${prefix}/data`,
metadata: `${prefix}/meta`,
auth: `${prefix}/auth`,
packages: `${prefix}/packages`,
analytics: `${prefix}/analytics`,
// realtime deliberately absent (ADR-0076 D12, #2462): no
// /realtime HTTP surface is mounted anywhere — advertising
// it here made clients call a route that 404s.
workflow: `${prefix}/workflow`,
automation: `${prefix}/automation`,
ai: `${prefix}/ai`,
notifications: `${prefix}/notifications`,
i18n: `${prefix}/i18n`,
storage: `${prefix}/storage`,
ui: `${prefix}/ui`,
},
capabilities: {
// This standalone Hono surface registers CRUD + auth only (see
// below) — it does NOT mount the cross-object `/batch` route,
// which ships with `@objectstack/rest`. `declared === enforced`
// (#3298): report `transactionalBatch: false` so a client never
// drops its non-atomic fallback against a backend that lacks the
// endpoint. When `@objectstack/rest` is mounted it serves its own
// discovery, which reports the real value from the runtime engine.
transactionalBatch: { enabled: false },
},
};
// Discovery endpoints
rawApp.get('/.well-known/objectstack', (c: any) => c.redirect(`${prefix}/discovery`));
rawApp.get(`${prefix}/discovery`, (c: any) => c.json({ data: discovery }));
ctx.logger.info('Registered discovery endpoints', { prefix });
// ── Anonymous-deny gate (ADR-0056 D2, #2567) ──────────────────────────
// These raw `/data/:object` routes delegate straight to ObjectQL. They
// are only *shadowed* by the REST plugin's gated `/data` routes when
// that plugin registers the same paths FIRST — so before this gate the
// platform's anonymous posture depended on plugin registration order: a
// load-order change silently reopened anonymous data access with no test
// failing. Gating here makes the deny decision a property of THIS entry
// point too, so security no longer depends on who registered first.
//
// Secure-by-default: `requireAuth` mirrors `rest-server.ts`'s `?? true`
// (ADR-0056 D2). A deployment that intentionally serves data publicly
// sets `restConfig.api.requireAuth = false` (a boot warning is logged, as
// in the REST plugin). No-op in that case — the previously-public surface
// is unchanged. An authenticated / system caller always passes.
//
// `requireAuth` is not in the typed `api` shape (rest-server.ts reads it
// via the same `as any` cast), so widen locally.
const requireAuth =
(this.options.restConfig?.api as { requireAuth?: boolean } | undefined)?.requireAuth ?? true;
if (!requireAuth) {
ctx.logger.warn(
'Hono standard /data endpoints: requireAuth is OFF — anonymous callers can read/write object data. ' +
'This is a deliberate opt-out; set restConfig.requireAuth=true to deny anonymous access (ADR-0056 D2, #2567).',
);
}
// Returns a 401 Response when the caller is anonymous under the deny
// posture, else null (caller proceeds). Delegates the decision to the
// shared `shouldDenyAnonymous` (#2567) so every HTTP seam stays in
// lockstep. `isSystem` is never set on inbound HTTP (internal-only), so
// it cannot be forged to bypass this.
const denyAnonymous = (c: any, execCtx: any): Response | null =>
shouldDenyAnonymous({ requireAuth, userId: execCtx?.userId, isSystem: execCtx?.isSystem })
? c.json(ANONYMOUS_DENY_BODY, ANONYMOUS_DENY_STATUS)
: null;
// Basic CRUD data endpoints — delegate to ObjectQL service directly
const getObjectQL = () => ctx.getService<IDataEngine>('objectql');
// Helper: resolve ExecutionContext from request headers (cookie session
// or API key). Mirrors the runtime's resolveExecutionContext but
// self-contained to avoid a cross-package dep. We DO query the
// `sys_user_permission_set` link tables because hardcoding a single
// permission set name (e.g. `member_default`) would silently ignore
// any explicit admin / role assignment — including the platform-admin
// promotion seeded by `bootstrapPlatformAdmin`.
const resolveCtx = async (c: any): Promise<any | undefined> => {
try {
const authService: any = ctx.getService('auth');
if (!authService) return undefined;
let api: any = authService.api;
if (!api && typeof authService.getApi === 'function') {
api = await authService.getApi();
}
if (!api?.getSession) return undefined;
const session = await api.getSession({ headers: c.req.raw.headers });
if (!session?.user?.id) return undefined;
const userId = session.user.id;
const tenantId = session.session?.activeOrganizationId ?? undefined;
const permissions: string[] = [];
const roles: string[] = [];
try {
const ql = getObjectQL();
const sysCtx = { context: { isSystem: true } };
// Roles via sys_member (org-scoped if active org).
const memberRows = await ql?.find?.(
'sys_member',
{
where: tenantId
? { user_id: userId, organization_id: tenantId }
: { user_id: userId },
limit: 50,
...sysCtx,
} 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);
}
}
}
// User-scoped permission sets — match BOTH (a) the active
// org's link rows and (b) the cross-tenant rows
// (organization_id IS NULL) so the platform-admin
// promotion seeded by `bootstrapPlatformAdmin` applies
// regardless of the user's active org.
const upsRows = await ql?.find?.(
'sys_user_permission_set',
{ where: { user_id: userId }, limit: 100, ...sysCtx } 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, ...sysCtx } 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 whatever we resolved so far */
}
// Resolve fellow-org user IDs so identity-table RLS (sys_user
// org-members policy) can scope @-mention pickers, owner
// lookups and reviewer selectors to the active organization.
// Mirrors the resolvers in `@objectstack/rest` and
// `@objectstack/runtime` so all three REST entry-points
// produce a consistent ExecutionContext shape.
let orgUserIds: string[] = [userId];
if (tenantId) {
try {
const ql = getObjectQL();
const sysCtx = { context: { isSystem: true } };
const memberRows = await ql?.find?.(
'sys_member',
{ where: { organization_id: tenantId }, limit: 1000, ...sysCtx } as any,
).catch(() => []);
const ids = new Set<string>([userId]);
for (const m of (memberRows ?? []) as any[]) {
const uid = m.user_id ?? m.userId;
if (typeof uid === 'string' && uid.length > 0) ids.add(uid);
}
orgUserIds = Array.from(ids);
} catch {
/* fall back to self-only */
}
}
// Env-side AI-seat marker (simple model). The single-org env
// DB has no permission-set/org dimension for this — the seat is
// the boolean `sys_user.ai_access`. Read it with a GUARDED system
// query (NOT a better-auth additionalField: sys_user is
// better-auth-managed and better-auth SELECTs explicit columns,
// so an additionalField would make getSession query a possibly-
// missing column → broken auth; a guarded read can only no-op).
// When true, synthesize the `ai_seat` capability so the per-agent
// gate (evaluateAgentAccess → requires `ai_seat`) admits the user
// with no permission-set grant. Absent/false/missing-column →
// no synthesis (deny, as before).
if (!permissions.includes('ai_seat')) {
try {
const ql = getObjectQL();
const sysCtx = { context: { isSystem: true } };
const uRows = await ql?.find?.(
'sys_user',
{ where: { id: userId }, limit: 1, ...sysCtx } as any,
).catch(() => []);
// Turso returns sqlite booleans as 1/0; memory driver as boolean.
const aiAccess = (uRows?.[0] as any)?.ai_access;
if (aiAccess === true || aiAccess === 1 || aiAccess === '1') permissions.push('ai_seat');
} catch {
/* no ai_access column / query failed → no seat (safe) */
}
}
// [#2408 / #3361] Open the per-request `Server-Timing` disclosure
// gate for an admin/service principal — the standalone-surface analog
// of the runtime dispatcher's `timedResolveExecutionContext`. This
// self-contained resolver derives no posture rung, so derive one HERE,
// for the gate decision ONLY, from the resolved permission-set grants,
// and hand it to the shared `isPerfDisclosurePrincipal` predicate. The
// rung is computed onto a THROW-AWAY object, never the returned
// context: `ctx.posture` is an enforcement input (Layer 0 tier
// adjudication, ADR-0099 D1) and only the authoritative resolver may
// set it. A no-op when perf-tuning is off (no ambient gate).
const disclosurePosture = derivePosture({
isPlatformAdmin: permissions.includes(ADMIN_FULL_ACCESS),
isTenantAdmin: permissions.includes(ORGANIZATION_ADMIN),
});
if (isPerfDisclosurePrincipal({ isSystem: false, posture: disclosurePosture } as ExecutionContext)) {
allowPerfDisclosure();
}
return {
userId,
tenantId,
roles,
permissions,
isSystem: false,
org_user_ids: orgUserIds,
} as any;
} catch {
return undefined;
}
};
// Create
rawApp.post(`${prefix}/data/:object`, async (c: any) => {
const ql = getObjectQL();
if (!ql) return c.json({ error: 'Data service not available' }, 503);
const object = c.req.param('object');
const data = await c.req.json().catch(() => ({}));
const execCtx = await resolveCtx(c);
const denied = denyAnonymous(c, execCtx);
if (denied) return denied;
try {
const res = await ql.insert(object, data, { context: execCtx } as any);
const record = { ...data, ...res };
return c.json({ object, id: record.id, record });
} catch (err: any) {
if (err?.code === 'PERMISSION_DENIED' || err?.name === 'PermissionDeniedError') {
return c.json({ error: err.message ?? 'Forbidden' }, 403);
}
throw err;
}
});
// Get by ID
rawApp.get(`${prefix}/data/:object/:id`, async (c: any) => {
const ql = getObjectQL();
if (!ql) return c.json({ error: 'Data service not available' }, 503);
const object = c.req.param('object');
const id = c.req.param('id');
const execCtx = await resolveCtx(c);
const denied = denyAnonymous(c, execCtx);
if (denied) return denied;
try {
let all = await ql.find(object, { context: execCtx } as any);
if (!all) all = [];
const match = all.find((i: any) => i.id === id);
return match ? c.json({ object, id, record: match }) : c.json({ error: 'Not found' }, 404);
} catch (err: any) {
if (err?.code === 'PERMISSION_DENIED' || err?.name === 'PermissionDeniedError') {
return c.json({ error: err.message ?? 'Forbidden' }, 403);
}
throw err;
}
});
// Find / List
rawApp.get(`${prefix}/data/:object`, async (c: any) => {
const ql = getObjectQL();
if (!ql) return c.json({ error: 'Data service not available' }, 503);
const object = c.req.param('object');
const execCtx = await resolveCtx(c);
const denied = denyAnonymous(c, execCtx);
if (denied) return denied;
try {
let all = await ql.find(object, { context: execCtx } as any);
if (!Array.isArray(all) && all && (all as any).value) all = (all as any).value;
if (!all) all = [];
return c.json({ object, records: all, total: all.length });
} catch (err: any) {
if (err?.code === 'PERMISSION_DENIED' || err?.name === 'PermissionDeniedError') {
return c.json({ error: err.message ?? 'Forbidden' }, 403);
}
throw err;
}
});
// Effective permissions for the current user — single aggregation
// endpoint that resolves session → roles → permission sets → merged
// field/object permissions. Frontend Field-Level Security (FLS)
// consumes this to gate form fields / list columns without having
// to replicate the server's role+permission-set resolution and
// most-permissive merge logic.
//
// Response shape (designed to mirror @object-ui/permissions
// expectations — see `PermissionSet` in @objectstack/spec):
// {
// userId, tenantId, roles, permissionSets,
// objects: Record<objectName, { allowCreate, allowRead, ... }>,
// fields: Record<"object.field", { readable, editable }>,
// }
//
// Returns `{authenticated:false}` (200) when no session is
// present, so the frontend can distinguish anon from error.
rawApp.get(`${prefix}/auth/me/permissions`, async (c: any) => {
const execCtx = await resolveCtx(c);
if (!execCtx?.userId) {
return c.json({ authenticated: false });
}
try {
const metadata: any = ctx.getService('metadata');
const evaluator: any = ctx.getService('security.permissions');
const bootstrap: any[] = (() => {
try { return ctx.getService<any[]>('security.bootstrapPermissionSets') ?? []; }
catch { return []; }
})();
const fallbackName: string | null = (() => {