-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathserve.ts
More file actions
1537 lines (1452 loc) · 70.8 KB
/
serve.ts
File metadata and controls
1537 lines (1452 loc) · 70.8 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 { Args, Command, Flags } from '@oclif/core';
import path from 'path';
import fs from 'fs';
import net from 'net';
import chalk from 'chalk';
import { bundleRequire } from 'bundle-require';
import { loadConfig } from '../utils/config.js';
import { isHostConfig, shouldBootWithLibrary } from '../utils/plugin-detection.js';
import {
printHeader,
printKV,
printSuccess,
printError,
printStep,
printInfo,
printServerReady,
} from '../utils/format.js';
import {
STUDIO_PATH,
resolveStudioPath,
hasStudioDist,
createStudioStaticPlugin,
} from '../utils/studio.js';
import {
ACCOUNT_PATH,
resolveAccountPath,
hasAccountDist,
createAccountStaticPlugin,
} from '../utils/account.js';
import {
CONSOLE_PATH,
resolveConsolePath,
hasConsoleDist,
createConsoleStaticPlugin,
} from '../utils/console.js';
import dotenvFlow from 'dotenv-flow';
// Helper to find available port
const getAvailablePort = async (startPort: number): Promise<number> => {
const isPortAvailable = (port: number): Promise<boolean> => {
return new Promise((resolve) => {
const server = net.createServer();
server.once('error', (err: any) => {
resolve(false);
});
server.once('listening', () => {
server.close(() => resolve(true));
});
server.listen(port);
});
};
let port = startPort;
while (!(await isPortAvailable(port))) {
port++;
if (port > startPort + 100) {
throw new Error(`Could not find an available port starting from ${startPort}`);
}
}
return port;
};
export default class Serve extends Command {
static override description = 'Start ObjectStack server. Reads `objectstack.config.ts` if present; otherwise falls back to `dist/objectstack.json` (or OS_ARTIFACT_PATH, including http(s):// URLs) as a portable artifact.';
static override args = {
config: Args.string({ description: 'Configuration file path', required: false, default: 'objectstack.config.ts' }),
};
static override flags = {
port: Flags.string({ char: 'p', description: 'Server port', default: process.env.PORT ?? '3000' }),
dev: Flags.boolean({ description: 'Run in development mode (load devPlugins)' }),
ui: Flags.boolean({ description: 'Enable Studio UI at /_studio/ (default: true)', default: true, allowNo: true }),
console: Flags.boolean({
description: 'Mount the Console UI at /_console/ when the package is installed (default: true). When disabled, Studio claims the root redirect.',
default: true,
allowNo: true,
}),
server: Flags.boolean({ description: 'Start HTTP server plugin', default: true, allowNo: true }),
prebuilt: Flags.boolean({ description: 'Skip esbuild/bundle-require — load config as native ESM (production mode)', default: false }),
preset: Flags.string({
description: 'Plugin tier preset: minimal | default | full (overridden by config.tiers if set)',
options: ['minimal', 'default', 'full'],
}),
};
/**
* Capabilities auto-added to every app's `requires` for every preset
* EXCEPT `minimal`. These form the foundation that every server-side
* runtime expects to exist (background work, settings persistence,
* transactional mail, file uploads). Apps may still list these in
* `requires:` explicitly — duplicates are de-duped.
*
* Opt out: `objectstack serve --preset minimal`.
*
* Mirrored on hosted objectos per-project kernels by
* `mountDefaultProjectPlugins()` in `@objectstack/service-cloud`.
*/
static readonly ALWAYS_ON_CAPABILITIES: readonly string[] = Object.freeze([
'queue', 'job', 'cache', 'settings', 'email', 'storage',
]);
/**
* Auto-registered plugin tiers. Plugins explicitly listed in
* `config.plugins` are always loaded — tiers only gate the optional
* auto-registration blocks below (AIService, I18n, Studio UI, etc.).
*/
static readonly TIER_PRESETS: Record<string, string[]> = {
minimal: ['core'],
default: ['core', 'i18n', 'ui', 'auth'],
full: ['core', 'i18n', 'ui', 'ai', 'auth'],
};
async run(): Promise<void> {
const { args, flags } = await this.parse(Serve);
// When --dev is passed, set NODE_ENV early so any runtime modules
// imported below (and any deps that branch on NODE_ENV at import
// time) see development mode. We deliberately do NOT inherit
// NODE_ENV from the parent `os dev` spawn — see the note in
// commands/dev.ts for why.
if (flags.dev && !process.env.NODE_ENV) {
process.env.NODE_ENV = 'development';
}
let port = parseInt(flags.port);
try {
const availablePort = await getAvailablePort(port);
if (availablePort !== port) {
port = availablePort;
}
} catch (e) {
// Ignore error and try with original port
}
// Load .env files following Vite/Next.js convention
const mode = flags.dev ? 'development'
: (process.env.NODE_ENV === 'test' ? 'test'
: (process.env.NODE_ENV || 'production'));
dotenvFlow.config({ node_env: mode, silent: true });
const isDev = flags.dev || process.env.NODE_ENV === 'development';
const absolutePath = path.resolve(process.cwd(), args.config!);
const relativeConfig = path.relative(process.cwd(), absolutePath);
// ── Artifact-first fallback ──────────────────────────────────────
// If the user did not author an `objectstack.config.ts`, but a
// compiled artifact is reachable (explicit OS_ARTIFACT_PATH —
// including http(s):// URLs — or the canonical
// `<cwd>/dist/objectstack.json`), boot from that artifact alone.
// This is the same capability previously hard-coded in
// `apps/objectos/objectstack.config.ts`, lifted into the framework
// so any project can `objectstack start` against just a
// `dist/objectstack.json`.
const configMissing = !fs.existsSync(absolutePath);
let useArtifactFallback = false;
if (configMissing) {
const { resolveDefaultArtifactPath } = await import('@objectstack/runtime');
const artifactSource = resolveDefaultArtifactPath();
if (!artifactSource) {
printError(`Configuration file not found: ${absolutePath}`);
console.log(chalk.dim(' Hint: Run `objectstack init` to create a new project,'));
console.log(chalk.dim(' or run `objectstack build` first, or set OS_ARTIFACT_PATH.'));
this.exit(1);
}
useArtifactFallback = true;
}
// Quiet loading — only show a single spinner line
console.log('');
if (useArtifactFallback) {
console.log(chalk.dim(' No objectstack.config.ts found — booting from artifact (default host)...'));
} else {
console.log(chalk.dim(` Loading ${relativeConfig}...`));
}
// Track loaded plugins for summary
const loadedPlugins: string[] = [];
const shortPluginName = (raw: string) => {
// Map verbose internal IDs to short display names
if (raw.includes('objectql')) return 'ObjectQL';
if (raw.includes('driver') && raw.includes('memory')) return 'MemoryDriver';
if (raw.startsWith('plugin.app.')) return raw.replace('plugin.app.', '').split('.').pop() || raw;
if (raw.includes('hono')) return 'HonoServer';
return raw;
};
const trackPlugin = (name: string) => { loadedPlugins.push(shortPluginName(name)); };
// Track resolved storage driver + redacted URL for the startup banner.
let resolvedDriverLabel: string | undefined;
let resolvedDatabaseUrl: string | undefined;
const redactDbUrl = (url: string | undefined): string | undefined => {
if (!url) return undefined;
try {
// Redact passwords inside connection URLs: protocol://user:****@host/db
return url.replace(/(\/\/[^/@:]+):[^/@]+@/, '$1:****@');
} catch {
return url;
}
};
// Save original console/stdout methods — we'll suppress noise during boot
const originalConsoleLog = console.log;
const originalConsoleDebug = console.debug;
const origStdoutWrite = process.stdout.write.bind(process.stdout);
let bootQuiet = false;
const restoreOutput = () => {
bootQuiet = false;
process.stdout.write = origStdoutWrite;
console.log = originalConsoleLog;
console.debug = originalConsoleDebug;
};
const portShifted = parseInt(flags.port) !== port;
try {
// ── Suppress ALL runtime noise during boot ────────────────────
// Multiple sources write to stdout during startup:
// • Pino-pretty (direct process.stdout.write)
// • ObjectLogger browser fallback (console.log)
// • SchemaRegistry (console.log)
// We capture stdout entirely, then restore after runtime.start().
bootQuiet = true;
process.stdout.write = (chunk: any, ...rest: any[]) => {
if (bootQuiet) return true; // swallow
return (origStdoutWrite as any)(chunk, ...rest);
};
console.log = (...args: any[]) => { if (!bootQuiet) originalConsoleLog(...args); };
console.debug = (...args: any[]) => { if (!bootQuiet) originalConsoleDebug(...args); };
// Load configuration
// --prebuilt: load as native ESM (no esbuild, no bundle-require) —
// intended for production where the config has been compiled to dist/.
// --artifact-fallback: skip config loading entirely; the default-host
// helper will synthesize a stack from the artifact JSON below.
const { mod } = useArtifactFallback
? { mod: { default: {} as any } }
: flags.prebuilt
? { mod: await import(absolutePath.startsWith('/') ? `file://${absolutePath}` : absolutePath) }
: await bundleRequire({ filepath: absolutePath });
let config = mod.default || mod;
if (!useArtifactFallback && !config) {
throw new Error(`No default export found in ${args.config}`);
}
// Preserve module-level named exports (e.g. `onEnable`, `onDisable`
// lifecycle hooks) that would otherwise be dropped when we unwrap
// `mod.default`. Without this AppPlugin can never invoke runtime hooks
// declared as `export const onEnable = ...` alongside the default
// `defineStack(...)` export.
if (mod.default != null && config !== mod) {
const merged: any = { ...config };
for (const key of Object.keys(mod)) {
if (key === 'default' || key in merged) continue;
merged[key] = (mod as any)[key];
}
config = merged;
}
// Boot-mode dispatch: standalone goes directly through
// `@objectstack/runtime` (no cloud dependencies). runtime/cloud
// modes go through `@objectstack/service-cloud`.
if (useArtifactFallback || shouldBootWithLibrary(config)) {
// The boot stack returns only `{plugins, api}` — preserve the
// original stack metadata (notably `requires`, `analyticsCubes`,
// `tiers`) so the capability resolver further down can read it.
const originalConfig = config;
const resolvedMode = config.bootMode ?? process.env.OS_MODE ?? 'standalone';
if (useArtifactFallback) {
// Artifact-only boot — no objectstack.config.ts authored.
// Always use the default-host helper which is standalone-only
// and never depends on @objectstack/service-cloud.
const { createDefaultHostConfig } = await import('@objectstack/runtime');
const bootResult = await createDefaultHostConfig();
config = { ...originalConfig, ...bootResult } as any;
} else if (resolvedMode === 'standalone') {
const { createStandaloneStack } = await import('@objectstack/runtime');
const bootResult = await createStandaloneStack(config.standalone);
config = { ...originalConfig, ...bootResult } as any;
} else {
// Cloud / multi-project boot modes require @objectstack/service-cloud.
// When the package is unavailable (e.g. someone vendored only the
// public framework), fail with a clear, actionable error instead of
// an opaque module-not-found stack trace.
let createBootStack: any;
try {
({ createBootStack } = await import('@objectstack/service-cloud'));
} catch (err) {
throw new Error(
`Boot mode '${resolvedMode}' requires @objectstack/service-cloud, which is not installed.\n`
+ `Either install it (\`pnpm add @objectstack/service-cloud\`) or switch to bootMode='standalone'.\n`
+ `Underlying error: ${(err as Error)?.message ?? String(err)}`,
);
}
const bootResult = await createBootStack({
mode: config.bootMode,
runtime: config.runtime ?? config.project,
cloud: config.cloud,
});
config = { ...originalConfig, ...bootResult } as any;
}
}
// ── Resolve plugin tiers ──────────────────────────────────────
// Precedence: config.requires (capability declarations) >
// config.tiers > --preset > built-in default.
//
// `requires: ['ai', 'automation', ...]` is the recommended
// app-level way to declare platform dependencies. The CLI
// expands each capability name into the matching tier so the
// optional auto-registration blocks below light up without
// extra flags. Explicitly-listed `config.plugins` always load
// and shadow any capability resolution (i.e. an explicit
// instance wins over the auto-loader).
const presetName = flags.preset ?? (isDev ? 'default' : 'default');
const presetTiers = Serve.TIER_PRESETS[presetName] ?? Serve.TIER_PRESETS.default;
const requires: string[] = Array.isArray((config as any).requires)
? (config as any).requires.filter((c: unknown) => typeof c === 'string')
: [];
// Auth callbacks (password-reset, email-verification, magic-link,
// invitation) depend on the email service. Auto-pull `email` when
// `auth` is required so transactional mail works out of the box
// (LogTransport fallback when no provider is configured).
if (requires.includes('auth') && !requires.includes('email')) {
requires.push('email');
}
// Default capability slate — every preset except `minimal` gets the
// foundational services (queue + job + cache + settings + email +
// storage). Opt out with `objectstack serve --preset minimal`.
// Keeping `auth → email` above as a defensive rule for users who
// explicitly opt into `minimal` but still enable auth.
const ALWAYS_CAPS = Serve.ALWAYS_ON_CAPABILITIES;
if (presetName !== 'minimal') {
for (const cap of ALWAYS_CAPS) {
if (!requires.includes(cap)) requires.push(cap);
}
}
// The email + approvals + reports services schedule background work
// (durable retries, SLA escalation, scheduled digests). Auto-pull
// 'job' and 'queue' so plugins can opt into durable scheduling.
// IMPORTANT: prepend, so their plugins load (and their kernel:ready
// hooks fire) BEFORE consumers like email/approvals that subscribe
// to queues during their own kernel:ready phase.
const NEEDS_JOB_OR_QUEUE = ['email', 'approvals', 'reports', 'auth'];
if (NEEDS_JOB_OR_QUEUE.some((c) => requires.includes(c))) {
if (!requires.includes('queue')) requires.unshift('queue');
if (!requires.includes('job')) requires.unshift('job');
}
// Capability → tier: any capability that is gated by a tier
// here automatically opens that tier when listed in `requires`.
// Capabilities NOT in this map (e.g. `automation`, `analytics`,
// `audit`) bypass tier gating and are loaded directly by the
// capability-resolver block further down.
const CAPABILITY_TO_TIER: Record<string, string> = {
ai: 'ai',
i18n: 'i18n',
ui: 'ui',
auth: 'auth',
};
const requiredTiers = requires
.map((c) => CAPABILITY_TO_TIER[c])
.filter((t): t is string => typeof t === 'string');
const baseTiers =
Array.isArray((config as any).tiers) && (config as any).tiers.length > 0
? (config as any).tiers
: presetTiers;
const tiers: Set<string> = new Set([...baseTiers, ...requiredTiers]);
const tierEnabled = (t: string) => tiers.has(t);
const requiresCapability = (c: string) => requires.includes(c);
// Import ObjectStack runtime
const { Runtime } = await import('@objectstack/runtime');
// Set kernel logger to 'silent' — the CLI manages its own output
const loggerConfig = { level: 'silent' as const };
const runtime = new Runtime({
kernel: {
logger: loggerConfig
}
});
const kernel = runtime.getKernel();
// Load plugins from configuration
let plugins = config.plugins || [];
// Merge devPlugins if in dev mode
if (flags.dev && config.devPlugins) {
plugins = [...plugins, ...config.devPlugins];
}
// 1. Auto-register ObjectQL Plugin if objects define but plugins missing
const hasObjectQL = plugins.some((p: any) => p.name?.includes('objectql') || p.constructor?.name?.includes('ObjectQL'));
if (config.objects && !hasObjectQL) {
try {
const { ObjectQLPlugin } = await import('@objectstack/objectql');
await kernel.use(new ObjectQLPlugin());
trackPlugin('ObjectQL');
} catch (e: any) {
// silent
}
}
// 2. Auto-register storage driver
// Priority:
// 1. OS_DATABASE_DRIVER env var (explicit override)
// 2. URL scheme inferred from OS_DATABASE_URL
// mongodb://, mongodb+srv:// → mongodb
// postgres://, postgresql:// → postgres
// mysql://, mysql2:// → mysql
// libsql://, http(s):// + .turso. → turso
// file:, sqlite:, *.db, :memory: → sqlite
// 3. Default: InMemoryDriver in dev mode
const hasDriver = plugins.some((p: any) => p.name?.includes('driver') || p.constructor?.name?.includes('Driver'));
if (!hasDriver && config.objects) {
const explicitDriver = (process.env.OS_DATABASE_DRIVER ?? '').toLowerCase().trim();
const databaseUrl = process.env.OS_DATABASE_URL;
const inferDriverFromUrl = (url: string | undefined): string => {
if (!url) return '';
const u = url.trim();
if (/^mongodb(\+srv)?:\/\//i.test(u)) return 'mongodb';
if (/^postgres(ql)?:\/\//i.test(u)) return 'postgres';
if (/^mysql2?:\/\//i.test(u)) return 'mysql';
if (/^libsql:\/\//i.test(u)) return 'turso';
if (/^https?:\/\//i.test(u) && /\.turso\./i.test(u)) return 'turso';
if (/^file:/i.test(u) || /^sqlite:/i.test(u) || u === ':memory:' || /\.(db|sqlite|sqlite3)$/i.test(u)) return 'sqlite';
return '';
};
const driverType = explicitDriver || inferDriverFromUrl(databaseUrl);
try {
const { DriverPlugin } = await import('@objectstack/runtime');
if (driverType === 'mongodb' || driverType === 'mongo') {
const { MongoDBDriver } = await import('@objectstack/driver-mongodb');
await kernel.use(new DriverPlugin(new MongoDBDriver({
url: databaseUrl ?? 'mongodb://localhost:27017/objectstack',
}) as any));
trackPlugin('MongoDBDriver');
resolvedDriverLabel = 'MongoDBDriver';
resolvedDatabaseUrl = databaseUrl ?? 'mongodb://localhost:27017/objectstack';
} else if (driverType === 'sqlite' || driverType === 'sql') {
const { SqlDriver } = await import('@objectstack/driver-sql');
const filePath = (databaseUrl ?? ':memory:').replace(/^file:/, '').replace(/^sqlite:/, '').replace(/^sql:\/\//, '');
await kernel.use(new DriverPlugin(new SqlDriver({
client: 'better-sqlite3',
connection: { filename: filePath },
useNullAsDefault: true,
}) as any));
trackPlugin('SqlDriver');
resolvedDriverLabel = 'SqlDriver(sqlite)';
resolvedDatabaseUrl = databaseUrl ?? ':memory:';
} else if (driverType === 'postgres' || driverType === 'postgresql' || driverType === 'pg') {
const { SqlDriver } = await import('@objectstack/driver-sql');
await kernel.use(new DriverPlugin(new SqlDriver({
client: 'pg',
connection: databaseUrl,
pool: { min: 0, max: 5 },
}) as any));
trackPlugin('PostgresDriver');
resolvedDriverLabel = 'SqlDriver(pg)';
resolvedDatabaseUrl = databaseUrl;
} else if (driverType === 'mysql' || driverType === 'mysql2') {
const { SqlDriver } = await import('@objectstack/driver-sql');
await kernel.use(new DriverPlugin(new SqlDriver({
client: 'mysql2',
connection: databaseUrl,
pool: { min: 0, max: 5 },
}) as any));
trackPlugin('MySQLDriver');
resolvedDriverLabel = 'SqlDriver(mysql2)';
resolvedDatabaseUrl = databaseUrl;
} else if (driverType === 'turso' || driverType === 'libsql') {
const { TursoDriver } = await import('@objectstack/driver-turso');
await kernel.use(new DriverPlugin(new TursoDriver({
url: databaseUrl ?? 'file:./local.db',
authToken: process.env.OS_DATABASE_AUTH_TOKEN,
} as any) as any));
trackPlugin('TursoDriver');
resolvedDriverLabel = 'TursoDriver';
resolvedDatabaseUrl = databaseUrl ?? 'file:./local.db';
} else if (isDev) {
// Default in dev: in-memory driver
const { InMemoryDriver } = await import('@objectstack/driver-memory');
await kernel.use(new DriverPlugin(new InMemoryDriver()));
trackPlugin('MemoryDriver');
resolvedDriverLabel = 'InMemoryDriver';
resolvedDatabaseUrl = '(in-memory)';
}
} catch (e: any) {
// silent
}
}
// 3. Auto-register AppPlugin if config contains app definitions
// (objects / manifest / apps / flows / apis). Even host/aggregator
// configs (those whose `plugins` array contains instantiated plugins)
// need this wrap when they ALSO carry top-level metadata — otherwise
// top-level `flows`, `objects`, etc. never reach the ObjectQL registry
// and downstream services like AutomationServicePlugin start with 0 flows.
//
// To avoid double-registration when the host already wraps itself with
// an AppPlugin (e.g. apps/objectos's dev-workspace stack), we skip if
// any plugin in `plugins[]` is already an AppPlugin instance.
const hasAppPluginAlready = plugins.some(
(p: any) => p && (p.type === 'app' || p.constructor?.name === 'AppPlugin' || (p.name && typeof p.name === 'string' && p.name.startsWith('plugin.app.')))
);
const configHasMetadata = !!(
config.objects || config.manifest || config.apps || config.flows || config.apis
);
if (!hasAppPluginAlready && configHasMetadata) {
try {
const { AppPlugin } = await import('@objectstack/runtime');
await kernel.use(new AppPlugin(config));
trackPlugin('App');
} catch (e: any) {
// silent
}
}
// 3b. Auto-register I18nServicePlugin if config contains translations/i18n
// This ensures i18n REST routes work out of the box without manual plugin registration.
const hasI18nPlugin = plugins.some(
(p: any) => p.name === 'com.objectstack.service.i18n'
|| p.constructor?.name === 'I18nServicePlugin'
);
// Check the top-level config AND any nested AppPlugin bundles in the
// `plugins` array — host/aggregator configs (e.g. apps/objectos) don't
// define translations themselves but compose multiple `new AppPlugin(...)`
// entries, each carrying its own translations.
const pluginBundleHasTranslations = (bundle: any): boolean => {
if (!bundle || typeof bundle !== 'object') return false;
if (Array.isArray(bundle.translations) && bundle.translations.length > 0) return true;
if (bundle.i18n) return true;
if (bundle.manifest && (
(Array.isArray(bundle.manifest.translations) && bundle.manifest.translations.length > 0)
|| bundle.manifest.i18n
)) return true;
return false;
};
const anyAppPluginHasTranslations = plugins.some((p: any) => {
if (!p) return false;
// AppPlugin instances expose their bundle on `.bundle`
if (p.bundle && pluginBundleHasTranslations(p.bundle)) return true;
return false;
});
const configHasTranslations = (
pluginBundleHasTranslations(config)
|| anyAppPluginHasTranslations
);
if (!hasI18nPlugin && configHasTranslations && tierEnabled('i18n')) {
try {
// Dynamic import with variable to prevent tsc from resolving the optional package
const i18nPkg = '@objectstack/service-i18n';
const { I18nServicePlugin } = await import(/* webpackIgnore: true */ i18nPkg);
const i18nCfg = config.i18n || config.manifest?.i18n || {};
await kernel.use(new I18nServicePlugin({
defaultLocale: i18nCfg.defaultLocale,
fallbackLocale: i18nCfg.fallbackLocale || i18nCfg.defaultLocale || 'en',
}));
trackPlugin('I18nService');
} catch {
// @objectstack/service-i18n not installed — kernel memory fallback will handle i18n
}
} else if (!hasI18nPlugin && !configHasTranslations) {
// No translations and no explicit i18n plugin — this is fine, kernel fallback works
}
// Add HTTP server plugin BEFORE config plugins so that the
// http-server service is available for any plugin that needs it
// during init/start (e.g. AuthPlugin).
// Skip if config already contains a HonoServerPlugin to avoid
// duplicate registration.
const configHasHonoServer = plugins.some(
(p: any) => p.name === 'com.objectstack.server.hono' || p.constructor?.name === 'HonoServerPlugin'
);
if (flags.server && !configHasHonoServer) {
try {
const { HonoServerPlugin } = await import('@objectstack/plugin-hono-server');
const serverPlugin = new HonoServerPlugin({ port });
await kernel.use(serverPlugin);
trackPlugin('HonoServer');
} catch (e: any) {
console.warn(chalk.yellow(` ⚠ HTTP server plugin not available: ${e.message}`));
}
}
// Unknown-environment hostname guard.
//
// In multi-tenant cloud deployments (e.g. *.objectos.app), every
// public hostname is expected to map to a `sys_environment` row
// whose `hostname` column matches the request `Host`. Without this
// guard, an unknown subdomain like `demo-xxx.objectos.app` happily
// renders the control-plane Console SPA (served statically by
// createConsoleStaticPlugin), making the deployment look like an
// empty env rather than a missing one. We respond with a clear
// 404 instead.
//
// Activation: only when OS_ROOT_DOMAIN is set (e.g. "objectos.app").
// Reserved subdomains (cloud/www/api/docs/admin/app and the apex)
// bypass the check so platform surfaces keep working. Non-root
// hostnames (custom domains, localhost, *.workers.dev) pass through
// unchanged. Infra paths under /_admin or /.well-known are always
// allowed so health checks / cert flows aren't broken.
//
// Implemented as a Plugin so the middleware is wired during init
// (when http.server is available) and BEFORE start() runs on the
// Console static plugin / route-registering plugins. Hono's
// `app.use('*')` is order-independent for matching, so as long as
// the middleware is added before kernel:listening fires, it
// intercepts every request regardless of which plugin registered
// its handler.
const __rootDomain = (process.env.OS_ROOT_DOMAIN || '').trim().toLowerCase();
if (__rootDomain) {
const RESERVED = new Set(['', 'cloud', 'www', 'api', 'docs', 'admin', 'app']);
const guardPlugin: any = {
name: 'com.objectstack.cli.unknown-hostname-guard',
version: '1.0.0',
init: async (ctx: any) => {
try {
const httpServer: any = ctx.getService?.('http.server') ?? ctx.getService?.('http-server');
const rawApp = httpServer?.getRawApp?.();
if (!rawApp || typeof rawApp.use !== 'function') {
ctx.logger?.warn?.('[unknown-hostname-guard] http.server unavailable; guard not installed');
return;
}
const getEnvRegistry = () => {
try {
return ctx.getService?.('env-registry') ?? null;
} catch {
return null;
}
};
rawApp.use('*', async (c: any, next: any) => {
const rawHost = c.req.header('host') || '';
const host = rawHost.split(':')[0].toLowerCase();
if (!host) return next();
const isPlatformHost = host === __rootDomain || host.endsWith('.' + __rootDomain);
if (!isPlatformHost) return next();
const sub = host === __rootDomain ? '' : host.slice(0, -(__rootDomain.length + 1));
const head = sub.split('.').pop() || '';
if (RESERVED.has(sub) || RESERVED.has(head)) return next();
const p = c.req.path;
if (p.startsWith('/_admin/') || p === '/_admin' || p.startsWith('/.well-known/')) {
return next();
}
// Health and readiness endpoints must always answer 200
// regardless of whether the requested hostname maps to
// an env — Cloudflare's container probe (and any
// upstream load balancer) hits whatever Host header is
// currently bound to the worker. Returning 404 here on
// an unmapped hostname would kill the container.
if (p === '/api/v1/health' || p === '/api/v1/ready' || p === '/health') {
return next();
}
// Resolve env-registry lazily on each request — it may
// not be registered yet at init() time (registered by
// ObjectOSProjectPlugin's init which runs in plugin
// dependency order; we don't want to rely on ordering).
const registry: any = getEnvRegistry();
if (!registry || typeof registry.resolveByHostname !== 'function') {
return next();
}
try {
const hit = await registry.resolveByHostname(host);
if (hit) return next();
} catch {
return next();
}
// Content negotiation: browsers (Accept: text/html) get
// a clean 404 page; API clients (curl/fetch with JSON
// accept) get a structured error body.
const accept = (c.req.header('accept') || '').toLowerCase();
const wantsHtml = accept.includes('text/html');
if (wantsHtml) {
const safeHost = host.replace(/[<>&"']/g, (ch: string) => ((({
'<': '<', '>': '>', '&': '&', '"': '"', "'": ''',
} as Record<string, string>)[ch]) ?? ch));
const html = `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>404 — Environment not found</title>
<style>
:root { color-scheme: light dark; }
* { box-sizing: border-box; }
html, body { height: 100%; margin: 0; }
body {
font: 16px/1.5 -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
background: #fafafa;
color: #111;
display: grid;
place-items: center;
padding: 24px;
}
@media (prefers-color-scheme: dark) {
body { background: #0b0b0c; color: #e8e8e8; }
.card { background: #141417; border-color: #26262b; }
.host { background: #1c1c20; border-color: #2d2d33; color: #d0d0d0; }
.muted { color: #8b8b94; }
a { color: #6ea8fe; }
}
.card {
max-width: 520px;
width: 100%;
background: #fff;
border: 1px solid #e6e6e6;
border-radius: 12px;
padding: 32px;
box-shadow: 0 1px 2px rgba(0,0,0,.04);
text-align: center;
}
.code { font: 600 64px/1 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; margin: 0; letter-spacing: -2px; }
h1 { font-size: 20px; margin: 16px 0 8px; font-weight: 600; }
p { margin: 8px 0; }
.muted { color: #666; font-size: 14px; }
.host {
display: inline-block;
margin-top: 16px;
padding: 6px 12px;
background: #f4f4f5;
border: 1px solid #e4e4e7;
border-radius: 6px;
font: 13px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
color: #444;
word-break: break-all;
}
a { color: #2563eb; text-decoration: none; }
a:hover { text-decoration: underline; }
</style>
</head>
<body>
<main class="card">
<p class="code">404</p>
<h1>Environment not found</h1>
<p class="muted">No ObjectStack environment is bound to this hostname.</p>
<div class="host">${safeHost}</div>
<p class="muted" style="margin-top:24px">
If you own this domain, bind it to an environment in the
<a href="https://cloud.objectos.app/">ObjectStack Cloud console</a>.
</p>
</main>
</body>
</html>`;
return c.html(html, 404);
}
return c.json(
{
error: 'environment_not_found',
message: `No environment is bound to hostname '${host}'.`,
hostname: host,
},
404,
);
});
ctx.logger?.info?.('[unknown-hostname-guard] installed', { rootDomain: __rootDomain });
} catch (err: any) {
ctx.logger?.warn?.('[unknown-hostname-guard] install failed', { error: err?.message ?? err });
}
},
};
try {
await kernel.use(guardPlugin);
trackPlugin('UnknownHostnameGuard');
} catch {
// Best-effort.
}
}
// 5. Auto-register Studio single-project signal in dev mode.
//
// `objectstack dev` runs a vanilla user stack (e.g. examples/app-crm)
// as a single project — there is no apps/cloud control plane and no
// org/project picker is meaningful. Without this plugin Studio would
// fall back to its multi-project default and ask the user to "Create
// organization" before showing any platform metadata.
//
// The plugin only registers `GET /api/v1/studio/runtime-config`
// (returning `{ singleProject: true, defaultOrgId, defaultProjectId }`)
// — no identity seed, since CLI dev mode has no sys_organization /
// sys_project tables to write into. Skipped when the user config
// already carries a single-project / multi-project plugin.
const hasProjectModePlugin = plugins.some((p: any) => {
const n = p?.name ?? p?.constructor?.name ?? '';
return n === 'com.objectstack.studio.single-project'
|| n === 'com.objectstack.multi-project'
|| n === 'com.objectstack.studio.runtime-config';
});
if (isDev && !hasProjectModePlugin) {
try {
const cloudPkg = '@objectstack/service-cloud';
const { createSingleProjectPlugin } = await import(/* webpackIgnore: true */ cloudPkg);
await kernel.use(createSingleProjectPlugin({
projectId: process.env.OS_PROJECT_ID ?? 'proj_local',
orgId: process.env.OS_ORG_ID ?? 'org_local',
orgName: 'Local',
}));
trackPlugin('SingleProject');
} catch {
// @objectstack/service-cloud not installed — Studio falls back
// to multi-project mode (org/project picker visible).
}
}
// 5b. Auto-register AuthPlugin (and paired Security/Audit) when the
// 'auth' tier is enabled and no auth plugin is already configured.
// The Studio + Account portals expect /api/v1/auth/* to be served by
// better-auth via @objectstack/plugin-auth. Without this block,
// running `objectstack dev` on a vanilla user stack would 404 on
// login/register flows.
const hasAuthPlugin = plugins.some(
(p: any) => p?.name === 'com.objectstack.auth' || p?.constructor?.name === 'AuthPlugin'
);
if (!hasAuthPlugin && tierEnabled('auth')) {
try {
const authPkg = '@objectstack/plugin-auth';
const { AuthPlugin } = await import(/* webpackIgnore: true */ authPkg);
// In dev, fall back to a stable local secret so users don't have
// to set AUTH_SECRET just to try the login/register flow.
const secret = process.env.AUTH_SECRET
?? process.env.OS_AUTH_SECRET
?? (isDev ? 'dev-only-insecure-secret-change-me-in-production' : undefined);
// Guard: in cloud-connected runtime mode (e.g. objectos worker)
// the host kernel is a pure routing shell. Auth is owned by each
// per-project kernel (`ArtifactKernelFactory` injects an
// `AuthPlugin` per project against the project's own DB so users
// persist and stay isolated per subdomain). Injecting a host-level
// AuthPlugin here would compete with the per-project one — its
// shared OS_AUTH_SECRET would erroneously validate cookies across
// unrelated projects. Refuse to inject in runtime mode.
const cloudUrl = process.env.OS_CLOUD_URL?.trim();
const isRuntimeMode = !!cloudUrl && cloudUrl.toLowerCase() !== 'local' && cloudUrl.toLowerCase() !== 'off';
if (isRuntimeMode) {
console.warn(chalk.yellow(
' ⚠ AuthPlugin skipped on host kernel — runtime mode (OS_CLOUD_URL set).\n' +
' Auth is owned per-project by ArtifactKernelFactory (see service-cloud).'
));
} else if (!secret) {
console.warn(chalk.yellow(' ⚠ AuthPlugin skipped — set AUTH_SECRET to enable authentication in production'));
} else {
const baseUrl = process.env.AUTH_BASE_URL
?? process.env.OS_BASE_URL
?? `http://localhost:${port}`;
const socialProviders: Record<string, { clientId: string; clientSecret: string }> = {};
if (process.env.GOOGLE_CLIENT_ID && process.env.GOOGLE_CLIENT_SECRET)
socialProviders.google = { clientId: process.env.GOOGLE_CLIENT_ID, clientSecret: process.env.GOOGLE_CLIENT_SECRET };
if (process.env.GITHUB_CLIENT_ID && process.env.GITHUB_CLIENT_SECRET)
socialProviders.github = { clientId: process.env.GITHUB_CLIENT_ID, clientSecret: process.env.GITHUB_CLIENT_SECRET };
// Trusted origins (CSRF). better-auth uses a `*` glob that
// does NOT cross dot-separators, so `http://localhost:*` does
// not cover `http://<sub>.localhost:*`. Build the allow-list
// explicitly:
// - explicit `OS_TRUSTED_ORIGINS` (comma-separated) wins
// - else dev / preview defaults below
const trustedOrigins: string[] = [];
const explicitTrusted = process.env.OS_TRUSTED_ORIGINS?.trim();
if (explicitTrusted) {
explicitTrusted.split(',').map(s => s.trim()).filter(Boolean).forEach(o => {
if (!trustedOrigins.includes(o)) trustedOrigins.push(o);
});
}
// Always add the configured baseUrl so first-party redirects work.
try {
const u = new URL(baseUrl);
const baseOrigin = `${u.protocol}//${u.host}`;
if (!trustedOrigins.includes(baseOrigin)) trustedOrigins.push(baseOrigin);
} catch { /* ignore malformed baseUrl */ }
// Preview-mode subdomain wildcards (`<commit>--<pid>.<base>`).
// Honour `OS_PREVIEW_BASE_DOMAINS` (used by service-cloud's
// preview routing) and add `http://*.<base>:*` patterns.
const previewMode = (process.env.OS_PREVIEW_MODE ?? '').trim().toLowerCase();
const isPreviewMode = previewMode === '1' || previewMode === 'true' || previewMode === 'yes';
if (isPreviewMode) {
const baseDomains = (process.env.OS_PREVIEW_BASE_DOMAINS
?? 'preview.objectstack.ai,localhost')
.split(',').map(s => s.trim()).filter(Boolean);
for (const dom of baseDomains) {
const isLoopback = dom === 'localhost' || dom.endsWith('.localhost');
const scheme = isLoopback ? 'http' : 'https';
const portSuffix = isLoopback ? ':*' : '';
const wildcard = `${scheme}://*.${dom}${portSuffix}`;
if (!trustedOrigins.includes(wildcard)) trustedOrigins.push(wildcard);
}
}
// Dev convenience: keep `http://localhost:*` so plain
// `localhost:<port>` still works for non-preview Studio/Console.
if (isDev && !trustedOrigins.includes('http://localhost:*')) {
trustedOrigins.push('http://localhost:*');
}
// Per-project subdomains: when OS_ROOT_DOMAIN is set (multi-
// project hosting under `*.<root>`), every project hostname
// must be trusted by better-auth or sign-up/sign-in is
// rejected with "Invalid origin". Mirrors the OS_COOKIE_DOMAIN
// wildcard semantics — they are always set together.
const rootDomain = (process.env.OS_ROOT_DOMAIN ?? process.env.ROOT_DOMAIN)?.trim();
if (rootDomain) {
const wildcard = `https://*.${rootDomain}`;
if (!trustedOrigins.includes(wildcard)) trustedOrigins.push(wildcard);
}
// Collect application-defined org roles from the stack so
// Better-Auth's organization plugin accepts invitations to
// those roles (otherwise it 400s with `ROLE_NOT_FOUND`).
// Sources:
// - top-level `roles[]` (role hierarchy entries)
// - `permissions[]` PermissionSets where `isProfile === true`
// (these double as role identifiers; e.g. CRM Profiles)
// Real RBAC enforcement is still owned by SecurityPlugin, which
// matches these names against `permission` metadata entries.
const additionalOrgRoles = new Set<string>();
try {
const stackAny: any = config ?? {};
const collect = (arr: any) => {
if (!Array.isArray(arr)) return;
for (const r of arr) {
const n = typeof r === 'string' ? r : (r && typeof r.name === 'string' ? r.name : null);
if (n && n !== 'owner' && n !== 'admin' && n !== 'member') additionalOrgRoles.add(n);
}
};
collect(stackAny.roles);
if (Array.isArray(stackAny.permissions)) {
for (const p of stackAny.permissions) {
if (p && typeof p.name === 'string' && p.isProfile !== false) {
if (p.name !== 'owner' && p.name !== 'admin' && p.name !== 'member') additionalOrgRoles.add(p.name);
}
}
}
} catch {
// best-effort
}
await kernel.use(new AuthPlugin({
secret,
baseUrl,
socialProviders: Object.keys(socialProviders).length > 0 ? socialProviders : undefined,
trustedOrigins: trustedOrigins.length ? trustedOrigins : undefined,
...(additionalOrgRoles.size > 0 ? { additionalOrgRoles: Array.from(additionalOrgRoles) } : {}),
// Enable the admin plugin by default so the Setup app's
// ban/unban/set-password/impersonate/set-role row actions
// resolve to real endpoints. The plugin self-gates by role
// (only users whose `role` column is `admin` can hit
// /admin/* endpoints), so leaving it on for everyone is
// safe. Opt-out via OS_AUTH_ADMIN=false.
//
// Similarly enable twoFactor by default — it powers the
// Setup app's `sys_two_factor` toolbar actions (Enable 2FA,
// Disable 2FA). Opt-out via OS_AUTH_TWO_FACTOR=false.
//
// (api-key plugin: not yet shipped by better-auth — generic
// CRUD on `sys_api_key` handles row creation in the meantime.)
plugins: {
admin: String(process.env.OS_AUTH_ADMIN ?? 'true').toLowerCase() !== 'false',
twoFactor: String(process.env.OS_AUTH_TWO_FACTOR ?? 'true').toLowerCase() !== 'false',
},
advanced: process.env.OS_COOKIE_DOMAIN
? ({
crossSubDomainCookies: {
enabled: true,
domain: process.env.OS_COOKIE_DOMAIN,
},
} as any)
: undefined,
}));
trackPlugin('Auth');
// Pair: SecurityPlugin (RBAC) — optional
try {
const securityPkg = '@objectstack/plugin-security';
const { SecurityPlugin } = await import(/* webpackIgnore: true */ securityPkg);
// `OS_MULTI_TENANT=false` disables wildcard tenant_isolation
// RLS policies and the `organization_id` auto-injection on
// insert. Keep multi-tenant on by default — most ObjectStack
// deployments are multi-org.
const multiTenant = String(process.env.OS_MULTI_TENANT ?? 'true').toLowerCase() !== 'false';
await kernel.use(new SecurityPlugin({ multiTenant }));
trackPlugin('Security');
} catch {
// optional
}
// Pair: AuditPlugin — optional
try {
const auditPkg = '@objectstack/plugin-audit';
const { AuditPlugin } = await import(/* webpackIgnore: true */ auditPkg);
await kernel.use(new AuditPlugin());
trackPlugin('Audit');