@objectstack/runtime 7.8.0 → 8.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +530 -2170
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +123 -641
- package/dist/index.d.ts +123 -641
- package/dist/index.js +545 -2164
- package/dist/index.js.map +1 -1
- package/package.json +18 -18
package/dist/index.js
CHANGED
|
@@ -164,7 +164,7 @@ var init_seed_loader = __esm({
|
|
|
164
164
|
const config = request.config;
|
|
165
165
|
const allErrors = [];
|
|
166
166
|
const allResults = [];
|
|
167
|
-
const datasets = this.filterByEnv(request.
|
|
167
|
+
const datasets = this.filterByEnv(request.seeds, config.env);
|
|
168
168
|
if (datasets.length === 0) {
|
|
169
169
|
return this.buildEmptyResult(config, Date.now() - startTime);
|
|
170
170
|
}
|
|
@@ -234,10 +234,10 @@ var init_seed_loader = __esm({
|
|
|
234
234
|
}
|
|
235
235
|
async validate(datasets, config) {
|
|
236
236
|
const parsedConfig = SeedLoaderConfigSchema.parse({ ...config, dryRun: true });
|
|
237
|
-
return this.load({ datasets, config: parsedConfig });
|
|
237
|
+
return this.load({ seeds: datasets, config: parsedConfig });
|
|
238
238
|
}
|
|
239
239
|
// ==========================================================================
|
|
240
|
-
// Internal:
|
|
240
|
+
// Internal: Seed Loading
|
|
241
241
|
// ==========================================================================
|
|
242
242
|
async loadDataset(dataset, config, refMap, insertedRecords, deferredUpdates, allErrors) {
|
|
243
243
|
const objectName = dataset.object;
|
|
@@ -1657,7 +1657,7 @@ var init_app_plugin = __esm({
|
|
|
1657
1657
|
const seedLoader = new SeedLoaderService(ql, md, loggerRef);
|
|
1658
1658
|
const { SeedLoaderRequestSchema } = await import("@objectstack/spec/data");
|
|
1659
1659
|
const request = SeedLoaderRequestSchema.parse({
|
|
1660
|
-
|
|
1660
|
+
seeds: datasetsNow,
|
|
1661
1661
|
config: {
|
|
1662
1662
|
defaultMode: "upsert",
|
|
1663
1663
|
multiPass: true,
|
|
@@ -1677,7 +1677,7 @@ var init_app_plugin = __esm({
|
|
|
1677
1677
|
};
|
|
1678
1678
|
};
|
|
1679
1679
|
registerSvc("seed-replayer", replayer);
|
|
1680
|
-
ctx.logger.info(`[Seeder] Registered ${normalizedDatasets.length} datasets + replayer on kernel (total
|
|
1680
|
+
ctx.logger.info(`[Seeder] Registered ${normalizedDatasets.length} datasets + replayer on kernel (total seeds: ${merged.length})`);
|
|
1681
1681
|
} catch (e) {
|
|
1682
1682
|
ctx.logger.warn("[Seeder] Failed to register seed-datasets/seed-replayer service", { error: e?.message });
|
|
1683
1683
|
}
|
|
@@ -1693,7 +1693,7 @@ var init_app_plugin = __esm({
|
|
|
1693
1693
|
const seedLoader = new SeedLoaderService(ql, metadata, ctx.logger);
|
|
1694
1694
|
const { SeedLoaderRequestSchema } = await import("@objectstack/spec/data");
|
|
1695
1695
|
const request = SeedLoaderRequestSchema.parse({
|
|
1696
|
-
|
|
1696
|
+
seeds: normalizedDatasets,
|
|
1697
1697
|
config: { defaultMode: "upsert", multiPass: true, identity: seedIdentity }
|
|
1698
1698
|
});
|
|
1699
1699
|
const result = await seedLoader.load(request);
|
|
@@ -2167,154 +2167,8 @@ var init_standalone_stack = __esm({
|
|
|
2167
2167
|
}
|
|
2168
2168
|
});
|
|
2169
2169
|
|
|
2170
|
-
// src/cloud/environment-org-seed.ts
|
|
2171
|
-
var environment_org_seed_exports = {};
|
|
2172
|
-
__export(environment_org_seed_exports, {
|
|
2173
|
-
seedProjectMember: () => seedProjectMember,
|
|
2174
|
-
seedProjectOrganization: () => seedProjectOrganization
|
|
2175
|
-
});
|
|
2176
|
-
async function seedProjectOrganization(kernel, seed, logger) {
|
|
2177
|
-
if (!seed?.id || !seed?.name) return "skipped";
|
|
2178
|
-
try {
|
|
2179
|
-
const ql = kernel.getService("objectql");
|
|
2180
|
-
if (!ql?.insert || !ql?.find) {
|
|
2181
|
-
logger?.warn?.("[seedProjectOrganization] objectql service unavailable", { orgId: seed.id });
|
|
2182
|
-
return "skipped";
|
|
2183
|
-
}
|
|
2184
|
-
try {
|
|
2185
|
-
const existing = await ql.find(SYS_ORG, { where: { id: seed.id } });
|
|
2186
|
-
const rows = Array.isArray(existing) ? existing : existing?.value ?? [];
|
|
2187
|
-
if (Array.isArray(rows) && rows.length > 0) return "exists";
|
|
2188
|
-
} catch {
|
|
2189
|
-
}
|
|
2190
|
-
const nowIso = (/* @__PURE__ */ new Date()).toISOString();
|
|
2191
|
-
await ql.insert(SYS_ORG, {
|
|
2192
|
-
id: seed.id,
|
|
2193
|
-
name: seed.name,
|
|
2194
|
-
slug: seed.slug ?? null,
|
|
2195
|
-
logo: seed.logo ?? null,
|
|
2196
|
-
metadata: null,
|
|
2197
|
-
created_at: nowIso
|
|
2198
|
-
});
|
|
2199
|
-
logger?.info?.("[seedProjectOrganization] org seeded", {
|
|
2200
|
-
orgId: seed.id,
|
|
2201
|
-
name: seed.name
|
|
2202
|
-
});
|
|
2203
|
-
return "inserted";
|
|
2204
|
-
} catch (err) {
|
|
2205
|
-
logger?.warn?.("[seedProjectOrganization] failed (non-fatal)", {
|
|
2206
|
-
orgId: seed.id,
|
|
2207
|
-
error: err?.message
|
|
2208
|
-
});
|
|
2209
|
-
return "error";
|
|
2210
|
-
}
|
|
2211
|
-
}
|
|
2212
|
-
async function seedProjectMember(kernel, args, logger) {
|
|
2213
|
-
const { userId, organizationId } = args;
|
|
2214
|
-
const role = args.role ?? "member";
|
|
2215
|
-
if (!userId || !organizationId) return "skipped";
|
|
2216
|
-
try {
|
|
2217
|
-
const ql = kernel.getService("objectql");
|
|
2218
|
-
if (!ql?.insert || !ql?.find) {
|
|
2219
|
-
logger?.warn?.("[seedProjectMember] objectql service unavailable", { userId, organizationId });
|
|
2220
|
-
return "skipped";
|
|
2221
|
-
}
|
|
2222
|
-
try {
|
|
2223
|
-
const existing = await ql.find("sys_member", {
|
|
2224
|
-
where: { user_id: userId, organization_id: organizationId }
|
|
2225
|
-
});
|
|
2226
|
-
const rows = Array.isArray(existing) ? existing : existing?.value ?? [];
|
|
2227
|
-
if (Array.isArray(rows) && rows.length > 0) return "exists";
|
|
2228
|
-
} catch {
|
|
2229
|
-
}
|
|
2230
|
-
const nowIso = (/* @__PURE__ */ new Date()).toISOString();
|
|
2231
|
-
const memId = `mem_${Math.random().toString(36).slice(2, 14)}`;
|
|
2232
|
-
await ql.insert("sys_member", {
|
|
2233
|
-
id: memId,
|
|
2234
|
-
organization_id: organizationId,
|
|
2235
|
-
user_id: userId,
|
|
2236
|
-
role,
|
|
2237
|
-
created_at: nowIso
|
|
2238
|
-
});
|
|
2239
|
-
logger?.info?.("[seedProjectMember] member seeded", {
|
|
2240
|
-
userId,
|
|
2241
|
-
organizationId,
|
|
2242
|
-
role
|
|
2243
|
-
});
|
|
2244
|
-
return "inserted";
|
|
2245
|
-
} catch (err) {
|
|
2246
|
-
logger?.warn?.("[seedProjectMember] failed (non-fatal)", {
|
|
2247
|
-
userId,
|
|
2248
|
-
organizationId,
|
|
2249
|
-
error: err?.message
|
|
2250
|
-
});
|
|
2251
|
-
return "error";
|
|
2252
|
-
}
|
|
2253
|
-
}
|
|
2254
|
-
var SYS_ORG;
|
|
2255
|
-
var init_environment_org_seed = __esm({
|
|
2256
|
-
"src/cloud/environment-org-seed.ts"() {
|
|
2257
|
-
"use strict";
|
|
2258
|
-
SYS_ORG = "sys_organization";
|
|
2259
|
-
}
|
|
2260
|
-
});
|
|
2261
|
-
|
|
2262
|
-
// src/cloud/environment-owner-seed.ts
|
|
2263
|
-
var environment_owner_seed_exports = {};
|
|
2264
|
-
__export(environment_owner_seed_exports, {
|
|
2265
|
-
seedProjectOwner: () => seedProjectOwner
|
|
2266
|
-
});
|
|
2267
|
-
async function seedProjectOwner(kernel, seed, logger) {
|
|
2268
|
-
if (!seed?.userId || !seed?.email) return "skipped";
|
|
2269
|
-
try {
|
|
2270
|
-
const ql = kernel.getService("objectql");
|
|
2271
|
-
if (!ql?.insert || !ql?.find) {
|
|
2272
|
-
logger?.warn?.("[seedProjectOwner] objectql service unavailable", { userId: seed.userId });
|
|
2273
|
-
return "skipped";
|
|
2274
|
-
}
|
|
2275
|
-
try {
|
|
2276
|
-
const existing = await ql.find(SYS_USER, { where: { id: seed.userId } });
|
|
2277
|
-
const rows = Array.isArray(existing) ? existing : existing?.value ?? [];
|
|
2278
|
-
if (Array.isArray(rows) && rows.length > 0) return "exists";
|
|
2279
|
-
} catch {
|
|
2280
|
-
}
|
|
2281
|
-
const nowIso = (/* @__PURE__ */ new Date()).toISOString();
|
|
2282
|
-
await ql.insert(SYS_USER, {
|
|
2283
|
-
id: seed.userId,
|
|
2284
|
-
email: seed.email,
|
|
2285
|
-
name: seed.name ?? seed.email.split("@")[0] ?? "Owner",
|
|
2286
|
-
image: seed.image ?? null,
|
|
2287
|
-
// Cloud already verified the upstream email. Marking it verified
|
|
2288
|
-
// here is what unblocks better-auth's accountLinking check on
|
|
2289
|
-
// the first SSO callback (alongside the trustedProviders config
|
|
2290
|
-
// in plugin-auth/auth-manager.ts).
|
|
2291
|
-
email_verified: true,
|
|
2292
|
-
created_at: nowIso,
|
|
2293
|
-
updated_at: nowIso
|
|
2294
|
-
});
|
|
2295
|
-
logger?.info?.("[seedProjectOwner] owner seeded", {
|
|
2296
|
-
userId: seed.userId,
|
|
2297
|
-
email: seed.email
|
|
2298
|
-
});
|
|
2299
|
-
return "inserted";
|
|
2300
|
-
} catch (err) {
|
|
2301
|
-
logger?.warn?.("[seedProjectOwner] failed (non-fatal)", {
|
|
2302
|
-
userId: seed.userId,
|
|
2303
|
-
error: err?.message
|
|
2304
|
-
});
|
|
2305
|
-
return "error";
|
|
2306
|
-
}
|
|
2307
|
-
}
|
|
2308
|
-
var SYS_USER;
|
|
2309
|
-
var init_environment_owner_seed = __esm({
|
|
2310
|
-
"src/cloud/environment-owner-seed.ts"() {
|
|
2311
|
-
"use strict";
|
|
2312
|
-
SYS_USER = "sys_user";
|
|
2313
|
-
}
|
|
2314
|
-
});
|
|
2315
|
-
|
|
2316
2170
|
// src/index.ts
|
|
2317
|
-
import { ObjectKernel as
|
|
2171
|
+
import { ObjectKernel as ObjectKernel3 } from "@objectstack/core";
|
|
2318
2172
|
|
|
2319
2173
|
// src/runtime.ts
|
|
2320
2174
|
import { ObjectKernel } from "@objectstack/core";
|
|
@@ -2596,30 +2450,18 @@ import { getEnv, resolveLocale } from "@objectstack/core";
|
|
|
2596
2450
|
import { CoreServiceName } from "@objectstack/spec/system";
|
|
2597
2451
|
import { pluralToSingular, PLURAL_TO_SINGULAR } from "@objectstack/spec/shared";
|
|
2598
2452
|
|
|
2453
|
+
// src/security/api-key.ts
|
|
2454
|
+
import {
|
|
2455
|
+
API_KEY_PREFIX,
|
|
2456
|
+
hashApiKey,
|
|
2457
|
+
generateApiKey,
|
|
2458
|
+
extractApiKey,
|
|
2459
|
+
parseScopes,
|
|
2460
|
+
isExpired,
|
|
2461
|
+
resolveApiKeyPrincipal
|
|
2462
|
+
} from "@objectstack/core";
|
|
2463
|
+
|
|
2599
2464
|
// src/security/resolve-execution-context.ts
|
|
2600
|
-
function readHeader(headers, name) {
|
|
2601
|
-
if (!headers) return void 0;
|
|
2602
|
-
const lower = name.toLowerCase();
|
|
2603
|
-
if (typeof headers.get === "function") {
|
|
2604
|
-
const v = headers.get(name) ?? headers.get(lower);
|
|
2605
|
-
return v == null ? void 0 : String(v);
|
|
2606
|
-
}
|
|
2607
|
-
for (const key of Object.keys(headers)) {
|
|
2608
|
-
if (key.toLowerCase() === lower) {
|
|
2609
|
-
const v = headers[key];
|
|
2610
|
-
return Array.isArray(v) ? v[0] : v == null ? void 0 : String(v);
|
|
2611
|
-
}
|
|
2612
|
-
}
|
|
2613
|
-
return void 0;
|
|
2614
|
-
}
|
|
2615
|
-
function extractApiKey(headers) {
|
|
2616
|
-
const x = readHeader(headers, "x-api-key");
|
|
2617
|
-
if (x) return x.trim();
|
|
2618
|
-
const auth = readHeader(headers, "authorization");
|
|
2619
|
-
if (!auth) return void 0;
|
|
2620
|
-
const m = auth.match(/^ApiKey\s+(.+)$/i);
|
|
2621
|
-
return m ? m[1].trim() : void 0;
|
|
2622
|
-
}
|
|
2623
2465
|
function toHeaders(input) {
|
|
2624
2466
|
if (!input) return new Headers();
|
|
2625
2467
|
if (typeof Headers !== "undefined" && input instanceof Headers) return input;
|
|
@@ -2662,34 +2504,12 @@ async function resolveExecutionContext(opts) {
|
|
|
2662
2504
|
};
|
|
2663
2505
|
let userId;
|
|
2664
2506
|
let tenantId;
|
|
2665
|
-
const
|
|
2666
|
-
if (
|
|
2667
|
-
|
|
2668
|
-
|
|
2669
|
-
|
|
2670
|
-
if (
|
|
2671
|
-
const res = await verify({ body: { key: apiKey } });
|
|
2672
|
-
const payload = res?.key ?? res;
|
|
2673
|
-
if (payload?.userId) userId = payload.userId;
|
|
2674
|
-
if (payload?.organizationId) tenantId = payload.organizationId;
|
|
2675
|
-
if (Array.isArray(payload?.permissions)) {
|
|
2676
|
-
ctx.permissions.push(...payload.permissions);
|
|
2677
|
-
}
|
|
2678
|
-
if (Array.isArray(payload?.scopes)) {
|
|
2679
|
-
ctx.permissions.push(...payload.scopes);
|
|
2680
|
-
}
|
|
2681
|
-
}
|
|
2682
|
-
} catch {
|
|
2683
|
-
}
|
|
2684
|
-
if (!userId) {
|
|
2685
|
-
const ql2 = await opts.getQl();
|
|
2686
|
-
const rows = await tryFind(ql2, "sys_api_key", { key: apiKey, active: true }, 1);
|
|
2687
|
-
const row = rows[0];
|
|
2688
|
-
if (row) {
|
|
2689
|
-
userId = row.user_id ?? row.userId;
|
|
2690
|
-
tenantId = row.organization_id ?? row.organizationId;
|
|
2691
|
-
if (Array.isArray(row.scopes)) ctx.permissions.push(...row.scopes);
|
|
2692
|
-
}
|
|
2507
|
+
const keyPrincipal = await resolveApiKeyPrincipal(await opts.getQl(), headers);
|
|
2508
|
+
if (keyPrincipal) {
|
|
2509
|
+
userId = keyPrincipal.userId;
|
|
2510
|
+
tenantId = keyPrincipal.tenantId;
|
|
2511
|
+
for (const scope of keyPrincipal.scopes) {
|
|
2512
|
+
if (!ctx.permissions.includes(scope)) ctx.permissions.push(scope);
|
|
2693
2513
|
}
|
|
2694
2514
|
}
|
|
2695
2515
|
if (!userId) {
|
|
@@ -2965,6 +2785,253 @@ var _HttpDispatcher = class _HttpDispatcher {
|
|
|
2965
2785
|
}
|
|
2966
2786
|
throw { statusCode: 400, message: `Unknown data action: ${action}` };
|
|
2967
2787
|
}
|
|
2788
|
+
/**
|
|
2789
|
+
* Handle an MCP request over the Streamable HTTP transport (`/mcp`).
|
|
2790
|
+
*
|
|
2791
|
+
* Gating + auth (fail-closed):
|
|
2792
|
+
* - **opt-in**: only served when `OS_MCP_SERVER_ENABLED=true` (single-env
|
|
2793
|
+
* runtime). Multi-tenant cloud overrides this gate per env. When off we
|
|
2794
|
+
* return 404 so the surface isn't advertised.
|
|
2795
|
+
* - **auth**: requires a principal already resolved by
|
|
2796
|
+
* `resolveExecutionContext` (the `sys_api_key` Bearer/header path or a
|
|
2797
|
+
* session). Anonymous → 401.
|
|
2798
|
+
*
|
|
2799
|
+
* Execution: the MCP runtime builds a stateless per-request server whose
|
|
2800
|
+
* object-CRUD tools run through {@link callData} bound to THIS request's
|
|
2801
|
+
* ExecutionContext — i.e. the exact permission + RLS path the REST API
|
|
2802
|
+
* uses. An external agent can never exceed the key's authority.
|
|
2803
|
+
*/
|
|
2804
|
+
async handleMcp(body, context) {
|
|
2805
|
+
if (!_HttpDispatcher.isMcpEnabled()) {
|
|
2806
|
+
return { handled: true, response: this.error("MCP server is not enabled for this environment", 404) };
|
|
2807
|
+
}
|
|
2808
|
+
const mcp = await this.resolveService("mcp", context.environmentId);
|
|
2809
|
+
if (!mcp || typeof mcp.handleHttpRequest !== "function") {
|
|
2810
|
+
return { handled: true, response: this.error("MCP server is not available", 501) };
|
|
2811
|
+
}
|
|
2812
|
+
const ec = context.executionContext;
|
|
2813
|
+
if (!ec || !ec.userId && !ec.isSystem) {
|
|
2814
|
+
return { handled: true, response: this.error("Unauthorized: a valid API key is required", 401) };
|
|
2815
|
+
}
|
|
2816
|
+
const webRequest = this.toMcpWebRequest(context.request, body);
|
|
2817
|
+
if (!webRequest) {
|
|
2818
|
+
return { handled: true, response: this.error("MCP transport requires a standard HTTP request", 400) };
|
|
2819
|
+
}
|
|
2820
|
+
const bridge = this.buildMcpBridge(context);
|
|
2821
|
+
let webRes;
|
|
2822
|
+
try {
|
|
2823
|
+
webRes = await mcp.handleHttpRequest(webRequest, { bridge, parsedBody: body });
|
|
2824
|
+
} catch (err) {
|
|
2825
|
+
return { handled: true, response: this.error(err?.message ?? "MCP request failed", 500) };
|
|
2826
|
+
}
|
|
2827
|
+
const headers = {};
|
|
2828
|
+
try {
|
|
2829
|
+
webRes.headers.forEach((v, k) => {
|
|
2830
|
+
headers[k] = v;
|
|
2831
|
+
});
|
|
2832
|
+
} catch {
|
|
2833
|
+
}
|
|
2834
|
+
const text = await webRes.text().catch(() => "");
|
|
2835
|
+
let responseBody = null;
|
|
2836
|
+
if (text) {
|
|
2837
|
+
const ct = headers["content-type"] ?? "";
|
|
2838
|
+
if (ct.includes("application/json")) {
|
|
2839
|
+
try {
|
|
2840
|
+
responseBody = JSON.parse(text);
|
|
2841
|
+
} catch {
|
|
2842
|
+
responseBody = text;
|
|
2843
|
+
}
|
|
2844
|
+
} else {
|
|
2845
|
+
responseBody = text;
|
|
2846
|
+
}
|
|
2847
|
+
}
|
|
2848
|
+
return { handled: true, response: { status: webRes.status, headers, body: responseBody } };
|
|
2849
|
+
}
|
|
2850
|
+
/** Whether the MCP HTTP surface is opted in for this single-env runtime. */
|
|
2851
|
+
static isMcpEnabled() {
|
|
2852
|
+
return typeof process !== "undefined" && process.env?.OS_MCP_SERVER_ENABLED === "true";
|
|
2853
|
+
}
|
|
2854
|
+
/**
|
|
2855
|
+
* Normalise the inbound request into a Web-standard `Request` for the MCP
|
|
2856
|
+
* transport. Accepts an already-Web `Request`, or a node/Hono-style req
|
|
2857
|
+
* (plain `headers` object, path-only `url`). Returns undefined only if the
|
|
2858
|
+
* shape is unusable. The body is carried separately via `parsedBody`, so a
|
|
2859
|
+
* GET/DELETE (no body) and a POST (JSON-RPC) both normalise cleanly.
|
|
2860
|
+
*/
|
|
2861
|
+
toMcpWebRequest(raw, parsedBody) {
|
|
2862
|
+
if (!raw) return void 0;
|
|
2863
|
+
if (typeof raw.headers?.get === "function" && typeof raw.url === "string" && typeof raw.method === "string") {
|
|
2864
|
+
return raw;
|
|
2865
|
+
}
|
|
2866
|
+
try {
|
|
2867
|
+
const method = String(raw.method ?? "POST").toUpperCase();
|
|
2868
|
+
const headers = new Headers();
|
|
2869
|
+
const h = raw.headers;
|
|
2870
|
+
if (h) {
|
|
2871
|
+
if (typeof h.forEach === "function") {
|
|
2872
|
+
h.forEach((v, k) => {
|
|
2873
|
+
if (v != null) headers.set(String(k), String(v));
|
|
2874
|
+
});
|
|
2875
|
+
} else {
|
|
2876
|
+
for (const k of Object.keys(h)) {
|
|
2877
|
+
const v = h[k];
|
|
2878
|
+
if (v != null) headers.set(k, Array.isArray(v) ? v.join(",") : String(v));
|
|
2879
|
+
}
|
|
2880
|
+
}
|
|
2881
|
+
}
|
|
2882
|
+
let url;
|
|
2883
|
+
try {
|
|
2884
|
+
url = new URL(String(raw.url)).toString();
|
|
2885
|
+
} catch {
|
|
2886
|
+
const host = headers.get("host") || "mcp.local";
|
|
2887
|
+
const path = typeof raw.url === "string" && raw.url ? raw.url : "/api/v1/mcp";
|
|
2888
|
+
url = `https://${host}${path.startsWith("/") ? path : `/${path}`}`;
|
|
2889
|
+
}
|
|
2890
|
+
const init = { method, headers };
|
|
2891
|
+
if (method !== "GET" && method !== "HEAD" && method !== "DELETE") {
|
|
2892
|
+
init.body = typeof parsedBody === "string" ? parsedBody : JSON.stringify(parsedBody ?? {});
|
|
2893
|
+
}
|
|
2894
|
+
return new Request(url, init);
|
|
2895
|
+
} catch {
|
|
2896
|
+
return void 0;
|
|
2897
|
+
}
|
|
2898
|
+
}
|
|
2899
|
+
/**
|
|
2900
|
+
* Build a principal-bound {@link McpDataBridge}: every method runs AS the
|
|
2901
|
+
* request's ExecutionContext through {@link callData} (RLS/permissions) and
|
|
2902
|
+
* the per-env metadata service. Keeps the MCP tool layer free of any direct
|
|
2903
|
+
* engine access.
|
|
2904
|
+
*/
|
|
2905
|
+
buildMcpBridge(context) {
|
|
2906
|
+
const ec = context.executionContext;
|
|
2907
|
+
const envId = context.environmentId;
|
|
2908
|
+
const driver = context.dataDriver;
|
|
2909
|
+
const callData = this.callData.bind(this);
|
|
2910
|
+
const getMeta = () => this.resolveService("metadata", envId);
|
|
2911
|
+
return {
|
|
2912
|
+
listObjects: async () => {
|
|
2913
|
+
const meta = await getMeta();
|
|
2914
|
+
const objs = await meta?.listObjects?.() ?? [];
|
|
2915
|
+
return objs.map((o) => ({
|
|
2916
|
+
name: o.name,
|
|
2917
|
+
label: o.label ?? o.name,
|
|
2918
|
+
fieldCount: o.fields ? Object.keys(o.fields).length : void 0
|
|
2919
|
+
}));
|
|
2920
|
+
},
|
|
2921
|
+
describeObject: async (name) => {
|
|
2922
|
+
const meta = await getMeta();
|
|
2923
|
+
const def = await meta?.getObject?.(name);
|
|
2924
|
+
if (!def) return null;
|
|
2925
|
+
const fields = def.fields ?? {};
|
|
2926
|
+
return {
|
|
2927
|
+
name: def.name,
|
|
2928
|
+
label: def.label ?? def.name,
|
|
2929
|
+
fields: Object.entries(fields).map(([k, f]) => ({
|
|
2930
|
+
name: k,
|
|
2931
|
+
type: f?.type,
|
|
2932
|
+
label: f?.label ?? k,
|
|
2933
|
+
required: f?.required ?? false
|
|
2934
|
+
})),
|
|
2935
|
+
enableFeatures: def.enable ?? {}
|
|
2936
|
+
};
|
|
2937
|
+
},
|
|
2938
|
+
query: async (object, o) => {
|
|
2939
|
+
const query = {};
|
|
2940
|
+
if (o?.where) query.where = o.where;
|
|
2941
|
+
if (o?.fields) query.fields = o.fields;
|
|
2942
|
+
if (typeof o?.limit === "number") query.limit = o.limit;
|
|
2943
|
+
if (typeof o?.offset === "number") query.offset = o.offset;
|
|
2944
|
+
if (o?.orderBy) query.orderBy = o.orderBy;
|
|
2945
|
+
return await callData("query", { object, query }, driver, envId, ec);
|
|
2946
|
+
},
|
|
2947
|
+
get: async (object, id) => {
|
|
2948
|
+
const res = await callData("get", { object, id }, driver, envId, ec);
|
|
2949
|
+
return res?.record ?? res ?? null;
|
|
2950
|
+
},
|
|
2951
|
+
create: async (object, data) => await callData("create", { object, data }, driver, envId, ec),
|
|
2952
|
+
update: async (object, id, data) => await callData("update", { object, id, data }, driver, envId, ec),
|
|
2953
|
+
remove: async (object, id) => await callData("delete", { object, id }, driver, envId, ec)
|
|
2954
|
+
};
|
|
2955
|
+
}
|
|
2956
|
+
/**
|
|
2957
|
+
* Generate a `sys_api_key` and return the raw secret EXACTLY ONCE
|
|
2958
|
+
* (`POST /keys`). This is the only mint path — the raw key is never stored
|
|
2959
|
+
* (only its sha256 hash) and never re-displayable.
|
|
2960
|
+
*
|
|
2961
|
+
* Security (zero-tolerance):
|
|
2962
|
+
* - Requires an authenticated principal; `user_id` is PINNED to that
|
|
2963
|
+
* caller and is NEVER read from the request body (no impersonation).
|
|
2964
|
+
* - Body is whitelisted to `name` (+ optional `expires_at`); any
|
|
2965
|
+
* `key` / `id` / `user_id` / `revoked` in the body is ignored, so a
|
|
2966
|
+
* caller cannot forge a known-secret or escalate.
|
|
2967
|
+
* - `scopes` are intentionally NOT accepted from the body in v1: the
|
|
2968
|
+
* verify path ADDS scopes to the principal's permissions, so honouring
|
|
2969
|
+
* arbitrary body scopes would be an escalation vector. A generated key
|
|
2970
|
+
* therefore acts exactly AS the caller (via `user_id` resolution).
|
|
2971
|
+
* Narrowing/scoped keys need subset-enforcement — deferred.
|
|
2972
|
+
* - The raw key and its hash never enter logs or error messages.
|
|
2973
|
+
* - The row is written with an elevated `{ isSystem: true }` context
|
|
2974
|
+
* because `sys_api_key` is protection-locked; safe because the row's
|
|
2975
|
+
* contents are fully server-controlled (user_id pinned to caller).
|
|
2976
|
+
*/
|
|
2977
|
+
async handleKeys(method, body, context) {
|
|
2978
|
+
if (method !== "POST") {
|
|
2979
|
+
return { handled: true, response: this.error("Method not allowed", 405) };
|
|
2980
|
+
}
|
|
2981
|
+
const ec = context.executionContext;
|
|
2982
|
+
if (!ec || !ec.userId) {
|
|
2983
|
+
return { handled: true, response: this.error("Unauthorized: sign in to generate an API key", 401) };
|
|
2984
|
+
}
|
|
2985
|
+
const rawName = typeof body?.name === "string" ? body.name.trim() : "";
|
|
2986
|
+
const name = rawName || "API Key";
|
|
2987
|
+
let expiresAt;
|
|
2988
|
+
if (body?.expires_at != null && body.expires_at !== "") {
|
|
2989
|
+
const ms = typeof body.expires_at === "number" ? body.expires_at < 1e12 ? body.expires_at * 1e3 : body.expires_at : Date.parse(String(body.expires_at));
|
|
2990
|
+
if (Number.isNaN(ms)) {
|
|
2991
|
+
return { handled: true, response: this.error("Invalid expires_at: must be a parseable date", 400) };
|
|
2992
|
+
}
|
|
2993
|
+
if (ms <= Date.now()) {
|
|
2994
|
+
return { handled: true, response: this.error("Invalid expires_at: must be in the future", 400) };
|
|
2995
|
+
}
|
|
2996
|
+
expiresAt = new Date(ms).toISOString();
|
|
2997
|
+
}
|
|
2998
|
+
const ql = await this.getObjectQLService(context.environmentId) ?? await this.resolveService("objectql", context.environmentId);
|
|
2999
|
+
if (!ql || typeof ql.insert !== "function") {
|
|
3000
|
+
return { handled: true, response: this.error("Data service not available", 503) };
|
|
3001
|
+
}
|
|
3002
|
+
const generated = generateApiKey();
|
|
3003
|
+
const row = {
|
|
3004
|
+
name,
|
|
3005
|
+
key: generated.hash,
|
|
3006
|
+
prefix: generated.prefix,
|
|
3007
|
+
user_id: ec.userId,
|
|
3008
|
+
revoked: false
|
|
3009
|
+
};
|
|
3010
|
+
if (expiresAt) row.expires_at = expiresAt;
|
|
3011
|
+
let inserted;
|
|
3012
|
+
try {
|
|
3013
|
+
inserted = await ql.insert("sys_api_key", row, { context: { isSystem: true } });
|
|
3014
|
+
} catch {
|
|
3015
|
+
return { handled: true, response: this.error("Failed to create API key", 500) };
|
|
3016
|
+
}
|
|
3017
|
+
const id = inserted?.id ?? (Array.isArray(inserted) ? inserted[0]?.id : void 0);
|
|
3018
|
+
return {
|
|
3019
|
+
handled: true,
|
|
3020
|
+
response: {
|
|
3021
|
+
status: 201,
|
|
3022
|
+
body: {
|
|
3023
|
+
success: true,
|
|
3024
|
+
data: {
|
|
3025
|
+
id,
|
|
3026
|
+
name,
|
|
3027
|
+
prefix: generated.prefix,
|
|
3028
|
+
key: generated.raw,
|
|
3029
|
+
...expiresAt ? { expires_at: expiresAt } : {}
|
|
3030
|
+
}
|
|
3031
|
+
}
|
|
3032
|
+
}
|
|
3033
|
+
};
|
|
3034
|
+
}
|
|
2968
3035
|
/**
|
|
2969
3036
|
* Parse a project UUID out of a scoped URL path such as
|
|
2970
3037
|
* `/api/v1/environments/abc-123/data/task` or `/projects/abc-123/meta`.
|
|
@@ -3251,7 +3318,11 @@ var _HttpDispatcher = class _HttpDispatcher {
|
|
|
3251
3318
|
realtime: hasWebSockets ? `${prefix}/realtime` : void 0,
|
|
3252
3319
|
notifications: hasNotification ? `${prefix}/notifications` : void 0,
|
|
3253
3320
|
ai: hasAi ? `${prefix}/ai` : void 0,
|
|
3254
|
-
i18n: hasI18n ? `${prefix}/i18n` : void 0
|
|
3321
|
+
i18n: hasI18n ? `${prefix}/i18n` : void 0,
|
|
3322
|
+
// MCP (Streamable HTTP) is opt-in per env — only advertised
|
|
3323
|
+
// when OS_MCP_SERVER_ENABLED=true so the surface isn't exposed
|
|
3324
|
+
// by default. The objectui Integrations page reads this.
|
|
3325
|
+
mcp: _HttpDispatcher.isMcpEnabled() ? `${prefix}/mcp` : void 0
|
|
3255
3326
|
};
|
|
3256
3327
|
const svcAvailable = (route, provider) => ({
|
|
3257
3328
|
enabled: true,
|
|
@@ -3514,7 +3585,8 @@ var _HttpDispatcher = class _HttpDispatcher {
|
|
|
3514
3585
|
if (protocol && typeof protocol.getMetaItem === "function") {
|
|
3515
3586
|
try {
|
|
3516
3587
|
const organizationId = await this.resolveActiveOrganizationId(_context);
|
|
3517
|
-
const
|
|
3588
|
+
const previewDrafts = query?.preview === "draft";
|
|
3589
|
+
const data = await protocol.getMetaItem({ type: singularType, name, packageId, organizationId, previewDrafts });
|
|
3518
3590
|
return { handled: true, response: this.success(data) };
|
|
3519
3591
|
} catch (e) {
|
|
3520
3592
|
}
|
|
@@ -3556,7 +3628,8 @@ var _HttpDispatcher = class _HttpDispatcher {
|
|
|
3556
3628
|
if (protocol && typeof protocol.getMetaItems === "function") {
|
|
3557
3629
|
try {
|
|
3558
3630
|
const organizationId = await this.resolveActiveOrganizationId(_context);
|
|
3559
|
-
const
|
|
3631
|
+
const previewDrafts = query?.preview === "draft";
|
|
3632
|
+
const data = await protocol.getMetaItems({ type: typeOrName, packageId, organizationId, previewDrafts });
|
|
3560
3633
|
if (data && (data.items !== void 0 || Array.isArray(data))) {
|
|
3561
3634
|
return { handled: true, response: this.success(data) };
|
|
3562
3635
|
}
|
|
@@ -3903,6 +3976,18 @@ var _HttpDispatcher = class _HttpDispatcher {
|
|
|
3903
3976
|
...organizationId ? { organizationId } : {},
|
|
3904
3977
|
...body?.actor ? { actor: body.actor } : {}
|
|
3905
3978
|
});
|
|
3979
|
+
try {
|
|
3980
|
+
const seedNames = (result?.published ?? []).filter((p) => p?.type === "seed").map((p) => p.name);
|
|
3981
|
+
if (seedNames.length > 0) {
|
|
3982
|
+
result.seedApplied = await this.applyPublishedSeeds(
|
|
3983
|
+
seedNames,
|
|
3984
|
+
organizationId,
|
|
3985
|
+
_context
|
|
3986
|
+
);
|
|
3987
|
+
}
|
|
3988
|
+
} catch (e) {
|
|
3989
|
+
result.seedApplied = { success: false, error: e?.message ?? "seed apply failed" };
|
|
3990
|
+
}
|
|
3906
3991
|
return { handled: true, response: this.success(result) };
|
|
3907
3992
|
} catch (e) {
|
|
3908
3993
|
return { handled: true, response: this.error(e.message, e.statusCode || 500) };
|
|
@@ -3910,6 +3995,24 @@ var _HttpDispatcher = class _HttpDispatcher {
|
|
|
3910
3995
|
}
|
|
3911
3996
|
return { handled: true, response: this.error("Draft publishing not supported", 501) };
|
|
3912
3997
|
}
|
|
3998
|
+
if (parts.length === 2 && parts[1] === "discard-drafts" && m === "POST") {
|
|
3999
|
+
const id = decodeURIComponent(parts[0]);
|
|
4000
|
+
const protocol = await this.resolveService("protocol");
|
|
4001
|
+
if (protocol && typeof protocol.discardPackageDrafts === "function") {
|
|
4002
|
+
try {
|
|
4003
|
+
const organizationId = await this.resolveActiveOrganizationId(_context);
|
|
4004
|
+
const result = await protocol.discardPackageDrafts({
|
|
4005
|
+
packageId: id,
|
|
4006
|
+
...organizationId ? { organizationId } : {},
|
|
4007
|
+
...body?.actor ? { actor: body.actor } : {}
|
|
4008
|
+
});
|
|
4009
|
+
return { handled: true, response: this.success(result) };
|
|
4010
|
+
} catch (e) {
|
|
4011
|
+
return { handled: true, response: this.error(e.message, e.statusCode || 500) };
|
|
4012
|
+
}
|
|
4013
|
+
}
|
|
4014
|
+
return { handled: true, response: this.error("Draft discarding not supported", 501) };
|
|
4015
|
+
}
|
|
3913
4016
|
if (parts.length === 2 && parts[1] === "revert" && m === "POST") {
|
|
3914
4017
|
const id = decodeURIComponent(parts[0]);
|
|
3915
4018
|
const metadataService = await this.getService(CoreServiceName.enum.metadata);
|
|
@@ -3935,9 +4038,27 @@ var _HttpDispatcher = class _HttpDispatcher {
|
|
|
3935
4038
|
}
|
|
3936
4039
|
if (parts.length === 1 && m === "DELETE") {
|
|
3937
4040
|
const id = decodeURIComponent(parts[0]);
|
|
3938
|
-
const
|
|
3939
|
-
|
|
3940
|
-
|
|
4041
|
+
const registryRemoved = registry.uninstallPackage(id);
|
|
4042
|
+
let persisted = void 0;
|
|
4043
|
+
const protocol = await this.resolveService("protocol");
|
|
4044
|
+
if (protocol && typeof protocol.deletePackage === "function") {
|
|
4045
|
+
try {
|
|
4046
|
+
const organizationId = await this.resolveActiveOrganizationId(_context);
|
|
4047
|
+
const keepData = query?.keepData === "true" || query?.keepData === "1";
|
|
4048
|
+
persisted = await protocol.deletePackage({
|
|
4049
|
+
packageId: id,
|
|
4050
|
+
...organizationId ? { organizationId } : {},
|
|
4051
|
+
...keepData ? { keepData: true } : {}
|
|
4052
|
+
});
|
|
4053
|
+
} catch (e) {
|
|
4054
|
+
return { handled: true, response: this.error(e.message, e.statusCode || 500) };
|
|
4055
|
+
}
|
|
4056
|
+
}
|
|
4057
|
+
const deletedCount = persisted?.deletedCount ?? 0;
|
|
4058
|
+
if (!registryRemoved && deletedCount === 0) {
|
|
4059
|
+
return { handled: true, response: this.error(`Package '${id}' not found`, 404) };
|
|
4060
|
+
}
|
|
4061
|
+
return { handled: true, response: this.success({ success: true, registryRemoved, persisted }) };
|
|
3941
4062
|
}
|
|
3942
4063
|
} catch (e) {
|
|
3943
4064
|
return { handled: true, response: this.error(e.message, e.statusCode || 500) };
|
|
@@ -4059,6 +4180,66 @@ var _HttpDispatcher = class _HttpDispatcher {
|
|
|
4059
4180
|
* Physical database addressing (database_url, database_driver, etc.)
|
|
4060
4181
|
* is stored directly on the sys_environment row.
|
|
4061
4182
|
*/
|
|
4183
|
+
/**
|
|
4184
|
+
* Apply just-published `seed` metadata: load each seed's rows into its
|
|
4185
|
+
* target object so publishing a seed draft makes the data live (the runtime
|
|
4186
|
+
* counterpart to staging it). Reads each seed body via the protocol, then
|
|
4187
|
+
* runs the {@link SeedLoaderService} for the active org. Best-effort and
|
|
4188
|
+
* idempotent (upsert) — callers must never let this fail the publish.
|
|
4189
|
+
*
|
|
4190
|
+
* Lives at the runtime layer (not in the objectql publish primitive)
|
|
4191
|
+
* because the seed loader needs the data engine + metadata service, which
|
|
4192
|
+
* objectql cannot depend on without a layering cycle.
|
|
4193
|
+
*/
|
|
4194
|
+
async applyPublishedSeeds(names, organizationId, _context) {
|
|
4195
|
+
const protocol = await this.resolveService("protocol");
|
|
4196
|
+
const metadata = await this.getService(CoreServiceName.enum.metadata);
|
|
4197
|
+
const ql = await this.resolveService("objectql");
|
|
4198
|
+
if (!protocol || typeof protocol.getMetaItem !== "function" || !ql || !metadata) {
|
|
4199
|
+
return { success: false, error: "seed apply: required services unavailable" };
|
|
4200
|
+
}
|
|
4201
|
+
const datasets = [];
|
|
4202
|
+
const readErrors = [];
|
|
4203
|
+
for (const name of names) {
|
|
4204
|
+
const attempts = organizationId ? [{ type: "seed", name, organizationId }, { type: "seed", name }] : [{ type: "seed", name }];
|
|
4205
|
+
let item;
|
|
4206
|
+
for (const args of attempts) {
|
|
4207
|
+
try {
|
|
4208
|
+
item = await protocol.getMetaItem(args);
|
|
4209
|
+
if (item) break;
|
|
4210
|
+
} catch (e) {
|
|
4211
|
+
readErrors.push(`read ${name}: ${e?.message ?? String(e)}`);
|
|
4212
|
+
}
|
|
4213
|
+
}
|
|
4214
|
+
const seed = item?.object && Array.isArray(item?.records) ? item : item?.item ?? item?.metadata ?? item?.body;
|
|
4215
|
+
if (seed?.object && Array.isArray(seed?.records)) {
|
|
4216
|
+
datasets.push(seed);
|
|
4217
|
+
} else {
|
|
4218
|
+
readErrors.push(`seed "${name}" body unreadable (keys: ${item ? Object.keys(item).join(",") : "none"})`);
|
|
4219
|
+
}
|
|
4220
|
+
}
|
|
4221
|
+
if (datasets.length === 0) {
|
|
4222
|
+
return { success: false, inserted: 0, updated: 0, error: "seed apply: no readable seed bodies", errors: readErrors };
|
|
4223
|
+
}
|
|
4224
|
+
const { SeedLoaderService: SeedLoaderService2 } = await Promise.resolve().then(() => (init_seed_loader(), seed_loader_exports));
|
|
4225
|
+
const { SeedLoaderRequestSchema } = await import("@objectstack/spec/data");
|
|
4226
|
+
const loader = new SeedLoaderService2(ql, metadata, this.logger ?? console);
|
|
4227
|
+
const request = SeedLoaderRequestSchema.parse({
|
|
4228
|
+
seeds: datasets,
|
|
4229
|
+
config: {
|
|
4230
|
+
defaultMode: "upsert",
|
|
4231
|
+
multiPass: true,
|
|
4232
|
+
...organizationId ? { organizationId } : {}
|
|
4233
|
+
}
|
|
4234
|
+
});
|
|
4235
|
+
const r = await loader.load(request);
|
|
4236
|
+
return {
|
|
4237
|
+
success: r.success,
|
|
4238
|
+
inserted: r.summary.totalInserted,
|
|
4239
|
+
updated: r.summary.totalUpdated,
|
|
4240
|
+
errors: [...readErrors, ...r.errors ?? []]
|
|
4241
|
+
};
|
|
4242
|
+
}
|
|
4062
4243
|
/**
|
|
4063
4244
|
* Resolve the calling user id from the request session, if any.
|
|
4064
4245
|
* Returns `undefined` for anonymous calls or when auth is not wired up.
|
|
@@ -4643,6 +4824,12 @@ var _HttpDispatcher = class _HttpDispatcher {
|
|
|
4643
4824
|
if (cleanPath.startsWith("/data")) {
|
|
4644
4825
|
return this.handleData(cleanPath.substring(5), method, body, query, context);
|
|
4645
4826
|
}
|
|
4827
|
+
if (cleanPath === "/mcp" || cleanPath.startsWith("/mcp/") || cleanPath.startsWith("/mcp?")) {
|
|
4828
|
+
return this.handleMcp(body, context);
|
|
4829
|
+
}
|
|
4830
|
+
if (cleanPath === "/keys" || cleanPath.startsWith("/keys/") || cleanPath.startsWith("/keys?")) {
|
|
4831
|
+
return this.handleKeys(method, body, context);
|
|
4832
|
+
}
|
|
4646
4833
|
if (cleanPath.startsWith("/graphql")) {
|
|
4647
4834
|
if (method === "POST") return this.handleGraphQL(body, context);
|
|
4648
4835
|
}
|
|
@@ -5355,6 +5542,28 @@ function createDispatcherPlugin(config = {}) {
|
|
|
5355
5542
|
errorResponse(err, res);
|
|
5356
5543
|
}
|
|
5357
5544
|
});
|
|
5545
|
+
const mountMcp = (method) => {
|
|
5546
|
+
const register = method === "GET" ? server.get : method === "DELETE" ? server.delete : server.post;
|
|
5547
|
+
register.call(server, `${prefix}/mcp`, async (req, res) => {
|
|
5548
|
+
try {
|
|
5549
|
+
const result = await dispatcher.dispatch(method, "/mcp", req.body, req.query, { request: req });
|
|
5550
|
+
sendResult(result, res);
|
|
5551
|
+
} catch (err) {
|
|
5552
|
+
errorResponse(err, res);
|
|
5553
|
+
}
|
|
5554
|
+
});
|
|
5555
|
+
};
|
|
5556
|
+
mountMcp("POST");
|
|
5557
|
+
mountMcp("GET");
|
|
5558
|
+
mountMcp("DELETE");
|
|
5559
|
+
server.post(`${prefix}/keys`, async (req, res) => {
|
|
5560
|
+
try {
|
|
5561
|
+
const result = await dispatcher.dispatch("POST", "/keys", req.body, req.query, { request: req });
|
|
5562
|
+
sendResult(result, res);
|
|
5563
|
+
} catch (err) {
|
|
5564
|
+
errorResponse(err, res);
|
|
5565
|
+
}
|
|
5566
|
+
});
|
|
5358
5567
|
server.get(`${prefix}/packages`, async (req, res) => {
|
|
5359
5568
|
try {
|
|
5360
5569
|
const result = await dispatcher.handlePackages("", "GET", {}, req.query, { request: req });
|
|
@@ -6000,1591 +6209,44 @@ var MiddlewareManager = class {
|
|
|
6000
6209
|
// src/index.ts
|
|
6001
6210
|
init_load_artifact_bundle();
|
|
6002
6211
|
|
|
6003
|
-
// src/cloud/
|
|
6004
|
-
var
|
|
6005
|
-
|
|
6006
|
-
|
|
6007
|
-
|
|
6008
|
-
|
|
6009
|
-
|
|
6010
|
-
this.ttlMs = config.ttlMs ?? 15 * 60 * 1e3;
|
|
6011
|
-
this.logger = config.logger ?? console;
|
|
6012
|
-
this.freshnessProbe = config.freshnessProbe;
|
|
6013
|
-
this.staleCheckIntervalMs = config.staleCheckIntervalMs ?? 1e4;
|
|
6014
|
-
}
|
|
6015
|
-
/** Returns the currently cached environmentIds (ordered by insertion). */
|
|
6016
|
-
keys() {
|
|
6017
|
-
return Array.from(this.cache.keys());
|
|
6018
|
-
}
|
|
6019
|
-
/** Cache size for diagnostics. */
|
|
6020
|
-
get size() {
|
|
6021
|
-
return this.cache.size;
|
|
6212
|
+
// src/cloud/cloud-url.ts
|
|
6213
|
+
var DEFAULT_CLOUD_URL = "https://cloud.objectos.ai";
|
|
6214
|
+
function resolveCloudUrl(explicit) {
|
|
6215
|
+
const raw = (explicit ?? process.env.OS_CLOUD_URL ?? "").trim();
|
|
6216
|
+
const lower = raw.toLowerCase();
|
|
6217
|
+
if (lower === "off" || lower === "none" || lower === "local" || lower === "disabled") {
|
|
6218
|
+
return "";
|
|
6022
6219
|
}
|
|
6023
|
-
|
|
6024
|
-
|
|
6025
|
-
|
|
6026
|
-
|
|
6027
|
-
|
|
6028
|
-
|
|
6029
|
-
|
|
6030
|
-
|
|
6031
|
-
|
|
6032
|
-
|
|
6033
|
-
if (this.ttlMs > 0 && Date.now() - existing.lastAccess > this.ttlMs) {
|
|
6034
|
-
await this.evict(environmentId);
|
|
6035
|
-
} else {
|
|
6036
|
-
if (this.freshnessProbe) {
|
|
6037
|
-
const now = Date.now();
|
|
6038
|
-
if (now - existing.lastStaleCheckAt >= this.staleCheckIntervalMs) {
|
|
6039
|
-
existing.lastStaleCheckAt = now;
|
|
6040
|
-
let stale = false;
|
|
6041
|
-
try {
|
|
6042
|
-
stale = await this.freshnessProbe(environmentId, existing.createdAt);
|
|
6043
|
-
} catch (err) {
|
|
6044
|
-
this.logger.warn?.("[KernelManager] freshness probe failed", { environmentId, err });
|
|
6045
|
-
}
|
|
6046
|
-
if (stale) {
|
|
6047
|
-
this.logger.info?.("[KernelManager] kernel evicted by freshness probe", { environmentId });
|
|
6048
|
-
await this.evict(environmentId);
|
|
6049
|
-
} else {
|
|
6050
|
-
existing.lastAccess = Date.now();
|
|
6051
|
-
return existing.kernel;
|
|
6052
|
-
}
|
|
6053
|
-
} else {
|
|
6054
|
-
existing.lastAccess = Date.now();
|
|
6055
|
-
return existing.kernel;
|
|
6056
|
-
}
|
|
6057
|
-
} else {
|
|
6058
|
-
existing.lastAccess = Date.now();
|
|
6059
|
-
return existing.kernel;
|
|
6060
|
-
}
|
|
6061
|
-
}
|
|
6062
|
-
}
|
|
6063
|
-
const inflight = this.pending.get(environmentId);
|
|
6064
|
-
if (inflight) return inflight;
|
|
6065
|
-
const promise = (async () => {
|
|
6066
|
-
const kernel = await this.factory.create(environmentId);
|
|
6067
|
-
const now = Date.now();
|
|
6068
|
-
this.cache.set(environmentId, { kernel, createdAt: now, lastAccess: now, lastStaleCheckAt: now });
|
|
6069
|
-
await this.enforceMaxSize();
|
|
6070
|
-
return kernel;
|
|
6071
|
-
})();
|
|
6072
|
-
this.pending.set(environmentId, promise);
|
|
6073
|
-
try {
|
|
6074
|
-
return await promise;
|
|
6075
|
-
} finally {
|
|
6076
|
-
this.pending.delete(environmentId);
|
|
6077
|
-
}
|
|
6220
|
+
const picked = raw || DEFAULT_CLOUD_URL;
|
|
6221
|
+
return picked.replace(/\/+$/, "");
|
|
6222
|
+
}
|
|
6223
|
+
|
|
6224
|
+
// src/cloud/marketplace-public-url.ts
|
|
6225
|
+
function resolveMarketplacePublicBaseUrl(explicit) {
|
|
6226
|
+
const raw = (explicit ?? process.env.OS_MARKETPLACE_PUBLIC_BASE_URL ?? "").trim();
|
|
6227
|
+
const lower = raw.toLowerCase();
|
|
6228
|
+
if (!raw || lower === "off" || lower === "none" || lower === "disabled" || lower === "false") {
|
|
6229
|
+
return "";
|
|
6078
6230
|
}
|
|
6079
|
-
|
|
6080
|
-
|
|
6081
|
-
|
|
6082
|
-
|
|
6083
|
-
|
|
6084
|
-
|
|
6085
|
-
|
|
6086
|
-
|
|
6087
|
-
|
|
6088
|
-
|
|
6089
|
-
|
|
6090
|
-
|
|
6091
|
-
}
|
|
6231
|
+
return raw.replace(/\/+$/, "");
|
|
6232
|
+
}
|
|
6233
|
+
function publicMarketplaceKeyForApiPath(pathname) {
|
|
6234
|
+
const prefix = "/api/v1/marketplace/packages";
|
|
6235
|
+
if (pathname === prefix) return "packages.json";
|
|
6236
|
+
if (!pathname.startsWith(`${prefix}/`)) return null;
|
|
6237
|
+
const tail = pathname.slice(prefix.length + 1);
|
|
6238
|
+
if (!tail) return null;
|
|
6239
|
+
const parts = tail.split("/");
|
|
6240
|
+
if (parts.length === 1) {
|
|
6241
|
+
const id = decodeURIComponent(parts[0] ?? "");
|
|
6242
|
+
if (!id) return null;
|
|
6243
|
+
return `packages/${encodeURIComponent(id)}.json`;
|
|
6092
6244
|
}
|
|
6093
|
-
|
|
6094
|
-
|
|
6095
|
-
const
|
|
6096
|
-
|
|
6097
|
-
|
|
6098
|
-
async enforceMaxSize() {
|
|
6099
|
-
while (this.cache.size > this.maxSize) {
|
|
6100
|
-
let oldestKey;
|
|
6101
|
-
let oldestAccess = Infinity;
|
|
6102
|
-
for (const [key, entry] of this.cache) {
|
|
6103
|
-
if (entry.lastAccess < oldestAccess) {
|
|
6104
|
-
oldestAccess = entry.lastAccess;
|
|
6105
|
-
oldestKey = key;
|
|
6106
|
-
}
|
|
6107
|
-
}
|
|
6108
|
-
if (!oldestKey) return;
|
|
6109
|
-
await this.evict(oldestKey);
|
|
6110
|
-
}
|
|
6111
|
-
}
|
|
6112
|
-
};
|
|
6113
|
-
|
|
6114
|
-
// src/cloud/artifact-api-client.ts
|
|
6115
|
-
var ArtifactApiClient = class {
|
|
6116
|
-
constructor(config) {
|
|
6117
|
-
this.hostnameCache = /* @__PURE__ */ new Map();
|
|
6118
|
-
this.artifactCache = /* @__PURE__ */ new Map();
|
|
6119
|
-
this.pendingHostname = /* @__PURE__ */ new Map();
|
|
6120
|
-
this.pendingArtifact = /* @__PURE__ */ new Map();
|
|
6121
|
-
if (!config.controlPlaneUrl) {
|
|
6122
|
-
throw new Error("[ArtifactApiClient] controlPlaneUrl is required");
|
|
6123
|
-
}
|
|
6124
|
-
this.base = config.controlPlaneUrl.replace(/\/+$/, "");
|
|
6125
|
-
this.apiKey = config.apiKey;
|
|
6126
|
-
this.cacheTtlMs = config.cacheTtlMs ?? 5 * 60 * 1e3;
|
|
6127
|
-
this.requestTimeoutMs = config.requestTimeoutMs ?? 1e4;
|
|
6128
|
-
this.fetchImpl = config.fetch ?? globalThis.fetch;
|
|
6129
|
-
this.logger = config.logger ?? console;
|
|
6130
|
-
if (typeof this.fetchImpl !== "function") {
|
|
6131
|
-
throw new Error("[ArtifactApiClient] global fetch is not available \u2014 provide config.fetch");
|
|
6132
|
-
}
|
|
6133
|
-
}
|
|
6134
|
-
/**
|
|
6135
|
-
* Resolve a hostname to its project. Returns `null` on 404 or
|
|
6136
|
-
* malformed responses. Errors (network / 5xx) are thrown so
|
|
6137
|
-
* upstream callers can retry.
|
|
6138
|
-
*/
|
|
6139
|
-
async resolveHostname(host) {
|
|
6140
|
-
const cached = this.hostnameCache.get(host);
|
|
6141
|
-
if (cached && cached.expiresAt > Date.now()) return cached.value;
|
|
6142
|
-
const inflight = this.pendingHostname.get(host);
|
|
6143
|
-
if (inflight) return inflight;
|
|
6144
|
-
const promise = (async () => {
|
|
6145
|
-
try {
|
|
6146
|
-
const url = `${this.base}/api/v1/cloud/resolve-hostname?host=${encodeURIComponent(host)}`;
|
|
6147
|
-
const res = await this.request(url);
|
|
6148
|
-
if (res === null) return null;
|
|
6149
|
-
const body = res.success === false ? null : res.data ?? res;
|
|
6150
|
-
if (!body || typeof body.environmentId !== "string" || !body.environmentId) return null;
|
|
6151
|
-
const value = {
|
|
6152
|
-
environmentId: body.environmentId,
|
|
6153
|
-
organizationId: body.organizationId,
|
|
6154
|
-
runtime: body.runtime
|
|
6155
|
-
};
|
|
6156
|
-
this.hostnameCache.set(host, { value, expiresAt: Date.now() + this.cacheTtlMs });
|
|
6157
|
-
return value;
|
|
6158
|
-
} finally {
|
|
6159
|
-
this.pendingHostname.delete(host);
|
|
6160
|
-
}
|
|
6161
|
-
})();
|
|
6162
|
-
this.pendingHostname.set(host, promise);
|
|
6163
|
-
return promise;
|
|
6164
|
-
}
|
|
6165
|
-
/**
|
|
6166
|
-
* Fetch the compiled artifact for a project.
|
|
6167
|
-
*
|
|
6168
|
-
* When `opts.commit` is set, requests that specific revision via the
|
|
6169
|
-
* existing `?commit=` query param. Different commits are cached
|
|
6170
|
-
* independently (the cache key includes the commit id) so the preview
|
|
6171
|
-
* runtime can hold multiple versions in memory simultaneously.
|
|
6172
|
-
*/
|
|
6173
|
-
async fetchArtifact(environmentId, opts) {
|
|
6174
|
-
const commit = opts?.commit?.trim() || "";
|
|
6175
|
-
const cacheKey = commit ? `${environmentId}@${commit}` : environmentId;
|
|
6176
|
-
const cached = this.artifactCache.get(cacheKey);
|
|
6177
|
-
if (cached && cached.expiresAt > Date.now()) return cached.value;
|
|
6178
|
-
const inflight = this.pendingArtifact.get(cacheKey);
|
|
6179
|
-
if (inflight) return inflight;
|
|
6180
|
-
const promise = (async () => {
|
|
6181
|
-
try {
|
|
6182
|
-
const qs = commit ? `?commit=${encodeURIComponent(commit)}` : "";
|
|
6183
|
-
const url = `${this.base}/api/v1/cloud/environments/${encodeURIComponent(environmentId)}/artifact${qs}`;
|
|
6184
|
-
const res = await this.request(url);
|
|
6185
|
-
if (res === null) return null;
|
|
6186
|
-
const body = res.success === false ? null : res.data ?? res;
|
|
6187
|
-
if (!body || typeof body !== "object") return null;
|
|
6188
|
-
if (!body.metadata) {
|
|
6189
|
-
this.logger.warn?.("[ArtifactApiClient] artifact response missing `metadata`", { environmentId, commit });
|
|
6190
|
-
return null;
|
|
6191
|
-
}
|
|
6192
|
-
const value = body;
|
|
6193
|
-
this.artifactCache.set(cacheKey, { value, expiresAt: Date.now() + this.cacheTtlMs });
|
|
6194
|
-
return value;
|
|
6195
|
-
} finally {
|
|
6196
|
-
this.pendingArtifact.delete(cacheKey);
|
|
6197
|
-
}
|
|
6198
|
-
})();
|
|
6199
|
-
this.pendingArtifact.set(cacheKey, promise);
|
|
6200
|
-
return promise;
|
|
6201
|
-
}
|
|
6202
|
-
/**
|
|
6203
|
-
* Resolve an 8-hex project short id (first 8 hex chars of the UUID,
|
|
6204
|
-
* dashes stripped) to the full environmentId. Used by the preview
|
|
6205
|
-
* runtime, which encodes project ids in subdomains.
|
|
6206
|
-
*
|
|
6207
|
-
* Returns `null` on 404 or ambiguity (the control plane returns 409
|
|
6208
|
-
* if the prefix matches more than one project).
|
|
6209
|
-
*/
|
|
6210
|
-
async lookupProjectByShortId(shortId) {
|
|
6211
|
-
const short = String(shortId ?? "").trim().toLowerCase();
|
|
6212
|
-
if (!/^[0-9a-f]{8,}$/.test(short)) return null;
|
|
6213
|
-
const url = `${this.base}/api/v1/cloud/environments-by-short-id/${encodeURIComponent(short)}`;
|
|
6214
|
-
const res = await this.request(url);
|
|
6215
|
-
if (res === null) return null;
|
|
6216
|
-
const body = res.success === false ? null : res.data ?? res;
|
|
6217
|
-
if (!body || typeof body.environmentId !== "string" || !body.environmentId) return null;
|
|
6218
|
-
return { environmentId: body.environmentId, organizationId: body.organizationId };
|
|
6219
|
-
}
|
|
6220
|
-
/**
|
|
6221
|
-
* Fetch the head commit of a branch. Returns the commit id (and the
|
|
6222
|
-
* matching revision row's `published_at` for cache-validity checks).
|
|
6223
|
-
* Reuses the existing `GET /cloud/environments/:id/branches` endpoint.
|
|
6224
|
-
*/
|
|
6225
|
-
async fetchBranchHead(environmentId, branchName) {
|
|
6226
|
-
const url = `${this.base}/api/v1/cloud/environments/${encodeURIComponent(environmentId)}/branches`;
|
|
6227
|
-
const res = await this.request(url);
|
|
6228
|
-
if (res === null) return null;
|
|
6229
|
-
const body = res.success === false ? null : res.data ?? res;
|
|
6230
|
-
const branches = Array.isArray(body?.branches) ? body.branches : [];
|
|
6231
|
-
const target = String(branchName ?? "").trim().toLowerCase();
|
|
6232
|
-
const found = branches.find((b) => String(b?.branch ?? "").toLowerCase() === target);
|
|
6233
|
-
if (!found?.headCommitId) return null;
|
|
6234
|
-
return { commitId: String(found.headCommitId), publishedAt: found.headPublishedAt ?? null };
|
|
6235
|
-
}
|
|
6236
|
-
/**
|
|
6237
|
-
* Cheap freshness probe — returns the env's `last_published_at`
|
|
6238
|
-
* (and best-effort current commit) without rebuilding the artifact.
|
|
6239
|
-
* Used by `KernelManager` on cache hits to detect when a per-env
|
|
6240
|
-
* kernel has been invalidated by an upstream change (marketplace
|
|
6241
|
-
* install/uninstall, artifact publish) so it can be rebuilt
|
|
6242
|
-
* without waiting for the 15-minute LRU TTL to expire.
|
|
6243
|
-
*
|
|
6244
|
-
* Returns `null` on definitive 404 / unknown env. Errors propagate
|
|
6245
|
-
* (caller decides whether to treat unreachable cloud as fresh or
|
|
6246
|
-
* stale — typically fresh, so a brief outage doesn't churn every
|
|
6247
|
-
* cached kernel).
|
|
6248
|
-
*/
|
|
6249
|
-
async getFreshness(environmentId) {
|
|
6250
|
-
const url = `${this.base}/api/v1/cloud/environments/${encodeURIComponent(environmentId)}/freshness`;
|
|
6251
|
-
const res = await this.request(url);
|
|
6252
|
-
if (res === null) return null;
|
|
6253
|
-
const body = res.success === false ? null : res.data ?? res;
|
|
6254
|
-
if (!body || typeof body !== "object") return null;
|
|
6255
|
-
const envId = typeof body.environmentId === "string" ? body.environmentId : environmentId;
|
|
6256
|
-
const lastPublishedAt = typeof body.lastPublishedAt === "string" ? body.lastPublishedAt : null;
|
|
6257
|
-
const commitId = typeof body.commitId === "string" ? body.commitId : null;
|
|
6258
|
-
return { environmentId: envId, lastPublishedAt, commitId };
|
|
6259
|
-
}
|
|
6260
|
-
/** Drop cached entries for a project (and any matching hostname). */
|
|
6261
|
-
invalidate(environmentId) {
|
|
6262
|
-
this.artifactCache.delete(environmentId);
|
|
6263
|
-
const prefix = `${environmentId}@`;
|
|
6264
|
-
for (const key of Array.from(this.artifactCache.keys())) {
|
|
6265
|
-
if (key.startsWith(prefix)) this.artifactCache.delete(key);
|
|
6266
|
-
}
|
|
6267
|
-
for (const [host, entry] of this.hostnameCache) {
|
|
6268
|
-
if (entry.value.environmentId === environmentId) this.hostnameCache.delete(host);
|
|
6269
|
-
}
|
|
6270
|
-
}
|
|
6271
|
-
/** Drop everything. Used on shutdown / hot-reload. */
|
|
6272
|
-
clear() {
|
|
6273
|
-
this.hostnameCache.clear();
|
|
6274
|
-
this.artifactCache.clear();
|
|
6275
|
-
}
|
|
6276
|
-
async request(url) {
|
|
6277
|
-
const controller = typeof AbortController !== "undefined" ? new AbortController() : null;
|
|
6278
|
-
const timer = controller ? setTimeout(() => controller.abort(), this.requestTimeoutMs) : null;
|
|
6279
|
-
try {
|
|
6280
|
-
const res = await this.fetchImpl(url, {
|
|
6281
|
-
method: "GET",
|
|
6282
|
-
headers: this.buildHeaders(),
|
|
6283
|
-
signal: controller?.signal
|
|
6284
|
-
});
|
|
6285
|
-
if (res.status === 404) return null;
|
|
6286
|
-
if (!res.ok) {
|
|
6287
|
-
throw new Error(`[ArtifactApiClient] ${url} \u2192 HTTP ${res.status}`);
|
|
6288
|
-
}
|
|
6289
|
-
return await res.json();
|
|
6290
|
-
} finally {
|
|
6291
|
-
if (timer) clearTimeout(timer);
|
|
6292
|
-
}
|
|
6293
|
-
}
|
|
6294
|
-
buildHeaders() {
|
|
6295
|
-
const headers = {
|
|
6296
|
-
"accept": "application/json",
|
|
6297
|
-
"user-agent": "objectos-runtime"
|
|
6298
|
-
};
|
|
6299
|
-
if (this.apiKey) headers["authorization"] = `Bearer ${this.apiKey}`;
|
|
6300
|
-
return headers;
|
|
6301
|
-
}
|
|
6302
|
-
};
|
|
6303
|
-
|
|
6304
|
-
// src/cloud/artifact-environment-registry.ts
|
|
6305
|
-
import { resolve as resolvePathNode } from "path";
|
|
6306
|
-
var ArtifactEnvironmentRegistry = class {
|
|
6307
|
-
constructor(config) {
|
|
6308
|
-
this.hostnameCache = /* @__PURE__ */ new Map();
|
|
6309
|
-
this.idCache = /* @__PURE__ */ new Map();
|
|
6310
|
-
this.pending = /* @__PURE__ */ new Map();
|
|
6311
|
-
this.client = config.client;
|
|
6312
|
-
this.cacheTTL = config.cacheTtlMs ?? 5 * 60 * 1e3;
|
|
6313
|
-
this.logger = config.logger ?? console;
|
|
6314
|
-
}
|
|
6315
|
-
async resolveByHostname(host) {
|
|
6316
|
-
const cached = this.hostnameCache.get(host);
|
|
6317
|
-
if (cached && cached.expiresAt > Date.now()) {
|
|
6318
|
-
return { environmentId: cached.environmentId, driver: cached.driver };
|
|
6319
|
-
}
|
|
6320
|
-
const key = `host:${host}`;
|
|
6321
|
-
const inflight = this.pending.get(key);
|
|
6322
|
-
if (inflight) {
|
|
6323
|
-
const result = await inflight;
|
|
6324
|
-
return result ? { environmentId: result.environmentId, driver: result.driver } : null;
|
|
6325
|
-
}
|
|
6326
|
-
const promise = (async () => {
|
|
6327
|
-
try {
|
|
6328
|
-
const resolved = await this.client.resolveHostname(host);
|
|
6329
|
-
if (!resolved) return null;
|
|
6330
|
-
const entry2 = await this.buildCacheEntry(resolved.environmentId, resolved.runtime, resolved.organizationId, host);
|
|
6331
|
-
if (!entry2) return null;
|
|
6332
|
-
this.hostnameCache.set(host, entry2);
|
|
6333
|
-
this.idCache.set(entry2.environmentId, entry2);
|
|
6334
|
-
return entry2;
|
|
6335
|
-
} catch (err) {
|
|
6336
|
-
this.logger.error?.("[ArtifactEnvironmentRegistry] resolveByHostname failed", {
|
|
6337
|
-
host,
|
|
6338
|
-
error: err?.message ?? err
|
|
6339
|
-
});
|
|
6340
|
-
return null;
|
|
6341
|
-
} finally {
|
|
6342
|
-
this.pending.delete(key);
|
|
6343
|
-
}
|
|
6344
|
-
})();
|
|
6345
|
-
this.pending.set(key, promise);
|
|
6346
|
-
const entry = await promise;
|
|
6347
|
-
return entry ? { environmentId: entry.environmentId, driver: entry.driver } : null;
|
|
6348
|
-
}
|
|
6349
|
-
async resolveById(environmentId) {
|
|
6350
|
-
const cached = this.idCache.get(environmentId);
|
|
6351
|
-
if (cached && cached.expiresAt > Date.now()) return cached.driver;
|
|
6352
|
-
const key = `id:${environmentId}`;
|
|
6353
|
-
const inflight = this.pending.get(key);
|
|
6354
|
-
if (inflight) {
|
|
6355
|
-
const result = await inflight;
|
|
6356
|
-
return result?.driver ?? null;
|
|
6357
|
-
}
|
|
6358
|
-
const promise = (async () => {
|
|
6359
|
-
try {
|
|
6360
|
-
const entry2 = await this.buildCacheEntry(environmentId, void 0, void 0, void 0);
|
|
6361
|
-
if (!entry2) return null;
|
|
6362
|
-
this.idCache.set(environmentId, entry2);
|
|
6363
|
-
if (entry2.project?.hostname) this.hostnameCache.set(entry2.project.hostname, entry2);
|
|
6364
|
-
return entry2;
|
|
6365
|
-
} catch (err) {
|
|
6366
|
-
this.logger.error?.("[ArtifactEnvironmentRegistry] resolveById failed", {
|
|
6367
|
-
environmentId,
|
|
6368
|
-
error: err?.message ?? err
|
|
6369
|
-
});
|
|
6370
|
-
return null;
|
|
6371
|
-
} finally {
|
|
6372
|
-
this.pending.delete(key);
|
|
6373
|
-
}
|
|
6374
|
-
})();
|
|
6375
|
-
this.pending.set(key, promise);
|
|
6376
|
-
const entry = await promise;
|
|
6377
|
-
return entry?.driver ?? null;
|
|
6378
|
-
}
|
|
6379
|
-
peekById(environmentId) {
|
|
6380
|
-
const cached = this.idCache.get(environmentId);
|
|
6381
|
-
if (cached && cached.expiresAt > Date.now()) {
|
|
6382
|
-
return { environmentId: cached.environmentId, driver: cached.driver, project: cached.project };
|
|
6383
|
-
}
|
|
6384
|
-
return null;
|
|
6385
|
-
}
|
|
6386
|
-
invalidate(environmentId) {
|
|
6387
|
-
this.idCache.delete(environmentId);
|
|
6388
|
-
for (const [host, entry] of this.hostnameCache) {
|
|
6389
|
-
if (entry.environmentId === environmentId) this.hostnameCache.delete(host);
|
|
6390
|
-
}
|
|
6391
|
-
this.client.invalidate(environmentId);
|
|
6392
|
-
}
|
|
6393
|
-
async buildCacheEntry(environmentId, runtimeFromHostname, orgIdFromHostname, hostname) {
|
|
6394
|
-
let runtime = runtimeFromHostname;
|
|
6395
|
-
let organizationId = orgIdFromHostname;
|
|
6396
|
-
let host = hostname;
|
|
6397
|
-
let artifactProjectId = environmentId;
|
|
6398
|
-
if (!runtime || !organizationId) {
|
|
6399
|
-
const artifact = await this.client.fetchArtifact(environmentId);
|
|
6400
|
-
if (!artifact) {
|
|
6401
|
-
this.logger.warn?.("[ArtifactEnvironmentRegistry] artifact not found", { environmentId });
|
|
6402
|
-
return null;
|
|
6403
|
-
}
|
|
6404
|
-
artifactProjectId = artifact.environmentId ?? environmentId;
|
|
6405
|
-
if (!runtime) runtime = artifact.runtime ?? extractRuntimeFromMetadata(artifact.metadata);
|
|
6406
|
-
if (!organizationId) organizationId = artifact.runtime?.organizationId;
|
|
6407
|
-
if (!host) host = artifact.runtime?.hostname;
|
|
6408
|
-
}
|
|
6409
|
-
if (!runtime || !runtime.databaseUrl || !runtime.databaseDriver) {
|
|
6410
|
-
this.logger.warn?.("[ArtifactEnvironmentRegistry] no runtime config for project", { environmentId });
|
|
6411
|
-
return null;
|
|
6412
|
-
}
|
|
6413
|
-
const driver = await createDriver(runtime.databaseDriver, runtime.databaseUrl, runtime.databaseAuthToken ?? "");
|
|
6414
|
-
const projectRow = {
|
|
6415
|
-
id: artifactProjectId,
|
|
6416
|
-
organization_id: organizationId,
|
|
6417
|
-
hostname: host,
|
|
6418
|
-
database_url: runtime.databaseUrl,
|
|
6419
|
-
database_driver: runtime.databaseDriver,
|
|
6420
|
-
metadata: runtime.metadata
|
|
6421
|
-
};
|
|
6422
|
-
return {
|
|
6423
|
-
environmentId: artifactProjectId,
|
|
6424
|
-
driver,
|
|
6425
|
-
project: projectRow,
|
|
6426
|
-
expiresAt: Date.now() + this.cacheTTL
|
|
6427
|
-
};
|
|
6428
|
-
}
|
|
6429
|
-
};
|
|
6430
|
-
function extractRuntimeFromMetadata(metadata) {
|
|
6431
|
-
const datasources = metadata?.datasources;
|
|
6432
|
-
if (!Array.isArray(datasources) || datasources.length === 0) return void 0;
|
|
6433
|
-
const mapping = metadata?.datasourceMapping;
|
|
6434
|
-
let preferredName;
|
|
6435
|
-
if (mapping) {
|
|
6436
|
-
const def = mapping.find((m) => m?.default === true);
|
|
6437
|
-
if (def?.datasource) preferredName = def.datasource;
|
|
6438
|
-
}
|
|
6439
|
-
const ds = preferredName ? datasources.find((d) => d?.name === preferredName) : datasources[0];
|
|
6440
|
-
if (!ds || typeof ds !== "object") return void 0;
|
|
6441
|
-
const config = ds.config ?? {};
|
|
6442
|
-
const url = config.url ?? config.connectionString ?? config.connection ?? config.filename;
|
|
6443
|
-
const driver = ds.driver;
|
|
6444
|
-
if (typeof driver !== "string" || typeof url !== "string") return void 0;
|
|
6445
|
-
return {
|
|
6446
|
-
databaseDriver: driver,
|
|
6447
|
-
databaseUrl: url,
|
|
6448
|
-
databaseAuthToken: typeof config.authToken === "string" ? config.authToken : void 0
|
|
6449
|
-
};
|
|
6450
|
-
}
|
|
6451
|
-
async function createDriver(driverType, databaseUrl, authToken) {
|
|
6452
|
-
switch (driverType) {
|
|
6453
|
-
case "libsql":
|
|
6454
|
-
case "turso": {
|
|
6455
|
-
let TursoDriver;
|
|
6456
|
-
try {
|
|
6457
|
-
({ TursoDriver } = await import("@objectstack/driver-turso"));
|
|
6458
|
-
} catch (primaryErr) {
|
|
6459
|
-
try {
|
|
6460
|
-
const { createRequire } = await import("module");
|
|
6461
|
-
const path = await import("path");
|
|
6462
|
-
const url = await import("url");
|
|
6463
|
-
const hostRequire = createRequire(path.join(process.cwd(), "noop.js"));
|
|
6464
|
-
const resolved = hostRequire.resolve("@objectstack/driver-turso");
|
|
6465
|
-
({ TursoDriver } = await import(url.pathToFileURL(resolved).href));
|
|
6466
|
-
} catch (fallbackErr) {
|
|
6467
|
-
throw new Error(
|
|
6468
|
-
`[ArtifactEnvironmentRegistry] libsql/turso driver requested but @objectstack/driver-turso is not resolvable. Install it from the cloud monorepo (cloud/packages/driver-turso) or via npm. (primary: ${primaryErr?.message ?? primaryErr}; fallback: ${fallbackErr?.message ?? fallbackErr})`
|
|
6469
|
-
);
|
|
6470
|
-
}
|
|
6471
|
-
}
|
|
6472
|
-
return new TursoDriver({ url: databaseUrl, authToken });
|
|
6473
|
-
}
|
|
6474
|
-
case "memory": {
|
|
6475
|
-
const { InMemoryDriver } = await import("@objectstack/driver-memory");
|
|
6476
|
-
const dbName = databaseUrl.replace(/^memory:\/\//, "").trim();
|
|
6477
|
-
const filePath = dbName ? resolvePathNode(process.cwd(), ".objectstack/data/projects", `${dbName}.json`) : void 0;
|
|
6478
|
-
return new InMemoryDriver({
|
|
6479
|
-
persistence: filePath ? { type: "file", path: filePath } : "file"
|
|
6480
|
-
});
|
|
6481
|
-
}
|
|
6482
|
-
case "sqlite":
|
|
6483
|
-
case "sql": {
|
|
6484
|
-
const filePath = databaseUrl.replace(/^file:/, "").replace(/^sql:\/\//, "");
|
|
6485
|
-
const { SqlDriver } = await import("@objectstack/driver-sql");
|
|
6486
|
-
return new SqlDriver({
|
|
6487
|
-
client: "better-sqlite3",
|
|
6488
|
-
connection: { filename: filePath },
|
|
6489
|
-
useNullAsDefault: true
|
|
6490
|
-
});
|
|
6491
|
-
}
|
|
6492
|
-
case "postgres":
|
|
6493
|
-
case "postgresql":
|
|
6494
|
-
case "pg": {
|
|
6495
|
-
const { SqlDriver } = await import("@objectstack/driver-sql");
|
|
6496
|
-
return new SqlDriver({
|
|
6497
|
-
client: "pg",
|
|
6498
|
-
connection: databaseUrl,
|
|
6499
|
-
pool: { min: 0, max: 5 }
|
|
6500
|
-
});
|
|
6501
|
-
}
|
|
6502
|
-
case "mongodb":
|
|
6503
|
-
case "mongo": {
|
|
6504
|
-
const { MongoDBDriver } = await import("@objectstack/driver-mongodb");
|
|
6505
|
-
return new MongoDBDriver({ url: databaseUrl });
|
|
6506
|
-
}
|
|
6507
|
-
default:
|
|
6508
|
-
throw new Error(`[ArtifactEnvironmentRegistry] Unsupported driver type: ${driverType}`);
|
|
6509
|
-
}
|
|
6510
|
-
}
|
|
6511
|
-
|
|
6512
|
-
// src/cloud/artifact-kernel-factory.ts
|
|
6513
|
-
init_driver_plugin();
|
|
6514
|
-
init_app_plugin();
|
|
6515
|
-
import { createHmac as createHmac2 } from "crypto";
|
|
6516
|
-
import { ObjectKernel as ObjectKernel3 } from "@objectstack/core";
|
|
6517
|
-
import { readEnvWithDeprecation as readEnvWithDeprecation3 } from "@objectstack/types";
|
|
6518
|
-
|
|
6519
|
-
// src/cloud/capability-loader.ts
|
|
6520
|
-
var CAPABILITY_PROVIDERS = {
|
|
6521
|
-
automation: {
|
|
6522
|
-
// Self-contained: AutomationServicePlugin seeds all built-in node
|
|
6523
|
-
// executors itself (ADR-0018), so no companion node-pack plugins.
|
|
6524
|
-
pkg: "@objectstack/service-automation",
|
|
6525
|
-
export: "AutomationServicePlugin"
|
|
6526
|
-
},
|
|
6527
|
-
ai: {
|
|
6528
|
-
pkg: "@objectstack/service-ai",
|
|
6529
|
-
export: "AIServicePlugin"
|
|
6530
|
-
},
|
|
6531
|
-
analytics: {
|
|
6532
|
-
pkg: "@objectstack/service-analytics",
|
|
6533
|
-
export: "AnalyticsServicePlugin",
|
|
6534
|
-
configKey: "analyticsCubes"
|
|
6535
|
-
},
|
|
6536
|
-
audit: {
|
|
6537
|
-
pkg: "@objectstack/plugin-audit",
|
|
6538
|
-
export: "AuditPlugin"
|
|
6539
|
-
},
|
|
6540
|
-
cache: {
|
|
6541
|
-
pkg: "@objectstack/service-cache",
|
|
6542
|
-
export: "CacheServicePlugin"
|
|
6543
|
-
},
|
|
6544
|
-
storage: {
|
|
6545
|
-
pkg: "@objectstack/service-storage",
|
|
6546
|
-
export: "StorageServicePlugin"
|
|
6547
|
-
},
|
|
6548
|
-
queue: {
|
|
6549
|
-
pkg: "@objectstack/service-queue",
|
|
6550
|
-
export: "QueueServicePlugin"
|
|
6551
|
-
},
|
|
6552
|
-
job: {
|
|
6553
|
-
pkg: "@objectstack/service-job",
|
|
6554
|
-
export: "JobServicePlugin"
|
|
6555
|
-
},
|
|
6556
|
-
messaging: {
|
|
6557
|
-
// Backs the `notify` flow node (ADR-0012): delivers to a user's
|
|
6558
|
-
// channels (inbox by default → `sys_inbox_message` rows).
|
|
6559
|
-
pkg: "@objectstack/service-messaging",
|
|
6560
|
-
export: "MessagingServicePlugin"
|
|
6561
|
-
},
|
|
6562
|
-
triggers: {
|
|
6563
|
-
// Concrete flow triggers — record-change (ObjectQL hooks) + schedule
|
|
6564
|
-
// (cron/interval via the job service; pair `triggers` with `job`).
|
|
6565
|
-
pkg: "@objectstack/plugin-trigger-record-change",
|
|
6566
|
-
export: "RecordChangeTriggerPlugin",
|
|
6567
|
-
extras: [{ pkg: "@objectstack/plugin-trigger-schedule", export: "ScheduleTriggerPlugin" }]
|
|
6568
|
-
},
|
|
6569
|
-
realtime: {
|
|
6570
|
-
pkg: "@objectstack/service-realtime",
|
|
6571
|
-
export: "RealtimeServicePlugin"
|
|
6572
|
-
},
|
|
6573
|
-
feed: {
|
|
6574
|
-
pkg: "@objectstack/service-feed",
|
|
6575
|
-
export: "FeedServicePlugin"
|
|
6576
|
-
},
|
|
6577
|
-
settings: {
|
|
6578
|
-
pkg: "@objectstack/service-settings",
|
|
6579
|
-
export: "SettingsServicePlugin"
|
|
6580
|
-
}
|
|
6581
|
-
};
|
|
6582
|
-
async function loadCapabilities(opts) {
|
|
6583
|
-
const { kernel, requires, bundle, environmentId } = opts;
|
|
6584
|
-
const logger = opts.logger ?? console;
|
|
6585
|
-
const installed = [];
|
|
6586
|
-
const resolved = [...new Set(requires)];
|
|
6587
|
-
if (resolved.includes("audit") && !resolved.includes("messaging")) {
|
|
6588
|
-
resolved.push("messaging");
|
|
6589
|
-
}
|
|
6590
|
-
for (const cap of resolved) {
|
|
6591
|
-
const spec = CAPABILITY_PROVIDERS[cap];
|
|
6592
|
-
if (!spec) {
|
|
6593
|
-
continue;
|
|
6594
|
-
}
|
|
6595
|
-
try {
|
|
6596
|
-
const mod = await import(
|
|
6597
|
-
/* webpackIgnore: true */
|
|
6598
|
-
spec.pkg
|
|
6599
|
-
);
|
|
6600
|
-
const Ctor = mod[spec.export];
|
|
6601
|
-
if (!Ctor) {
|
|
6602
|
-
logger.warn?.(
|
|
6603
|
-
`[CapabilityLoader] '${cap}': package '${spec.pkg}' did not export '${spec.export}'`,
|
|
6604
|
-
{ environmentId }
|
|
6605
|
-
);
|
|
6606
|
-
continue;
|
|
6607
|
-
}
|
|
6608
|
-
let arg;
|
|
6609
|
-
if (spec.configKey) {
|
|
6610
|
-
const v = bundle[spec.configKey];
|
|
6611
|
-
if (spec.configKey === "analyticsCubes") {
|
|
6612
|
-
arg = { cubes: Array.isArray(v) ? v : [] };
|
|
6613
|
-
} else if (v !== void 0) {
|
|
6614
|
-
arg = v;
|
|
6615
|
-
}
|
|
6616
|
-
}
|
|
6617
|
-
await kernel.use(arg !== void 0 ? new Ctor(arg) : new Ctor());
|
|
6618
|
-
installed.push(spec.export);
|
|
6619
|
-
if (spec.extras) {
|
|
6620
|
-
for (const ex of spec.extras) {
|
|
6621
|
-
try {
|
|
6622
|
-
const exMod = await import(
|
|
6623
|
-
/* webpackIgnore: true */
|
|
6624
|
-
ex.pkg
|
|
6625
|
-
);
|
|
6626
|
-
const ExCtor = exMod[ex.export];
|
|
6627
|
-
if (ExCtor) {
|
|
6628
|
-
await kernel.use(new ExCtor());
|
|
6629
|
-
installed.push(ex.export);
|
|
6630
|
-
}
|
|
6631
|
-
} catch {
|
|
6632
|
-
}
|
|
6633
|
-
}
|
|
6634
|
-
}
|
|
6635
|
-
logger.info?.(
|
|
6636
|
-
`[CapabilityLoader] '${cap}' installed (${spec.export}${spec.extras ? " + " + spec.extras.length + " extras" : ""})`,
|
|
6637
|
-
{ environmentId }
|
|
6638
|
-
);
|
|
6639
|
-
} catch (err) {
|
|
6640
|
-
const msg = err?.message ?? String(err);
|
|
6641
|
-
if (msg.includes("Cannot find module") || msg.includes("ERR_MODULE_NOT_FOUND")) {
|
|
6642
|
-
logger.warn?.(
|
|
6643
|
-
`[CapabilityLoader] '${cap}' requested but '${spec.pkg}' not installed in host \u2014 skipped`,
|
|
6644
|
-
{ environmentId }
|
|
6645
|
-
);
|
|
6646
|
-
} else {
|
|
6647
|
-
logger.error?.(
|
|
6648
|
-
`[CapabilityLoader] '${cap}' load failed: ${msg}`,
|
|
6649
|
-
{ environmentId }
|
|
6650
|
-
);
|
|
6651
|
-
}
|
|
6652
|
-
}
|
|
6653
|
-
}
|
|
6654
|
-
return installed;
|
|
6655
|
-
}
|
|
6656
|
-
|
|
6657
|
-
// src/cloud/platform-sso.ts
|
|
6658
|
-
import { createHmac, createHash } from "crypto";
|
|
6659
|
-
var PLATFORM_SSO_PROVIDER_ID = "objectstack-cloud";
|
|
6660
|
-
function derivePlatformSsoClientId(environmentId) {
|
|
6661
|
-
return `project_${environmentId}`;
|
|
6662
|
-
}
|
|
6663
|
-
function derivePlatformSsoClientSecret(baseSecret, environmentId) {
|
|
6664
|
-
return createHmac("sha256", baseSecret).update(`oauth-client:${environmentId}`).digest("hex");
|
|
6665
|
-
}
|
|
6666
|
-
function hashPlatformSsoClientSecret(plaintext) {
|
|
6667
|
-
return createHash("sha256").update(plaintext).digest("base64").replace(/=+$/, "").replace(/\+/g, "-").replace(/\//g, "_");
|
|
6668
|
-
}
|
|
6669
|
-
function buildPlatformSsoRedirectUri(hostname, basePath = "/api/v1/auth") {
|
|
6670
|
-
let host;
|
|
6671
|
-
if (hostname.startsWith("http://") || hostname.startsWith("https://")) {
|
|
6672
|
-
host = hostname;
|
|
6673
|
-
} else if (/(\.|^)localhost(:\d+)?$/i.test(hostname)) {
|
|
6674
|
-
const port = (process.env.OS_RUNTIME_PORT ?? "").trim();
|
|
6675
|
-
const hostWithPort = /:\d+$/.test(hostname) || !port ? hostname : `${hostname}:${port}`;
|
|
6676
|
-
host = `http://${hostWithPort}`;
|
|
6677
|
-
} else {
|
|
6678
|
-
host = `https://${hostname}`;
|
|
6679
|
-
}
|
|
6680
|
-
const trimmed = host.replace(/\/+$/, "");
|
|
6681
|
-
const path = basePath.replace(/\/+$/, "");
|
|
6682
|
-
return `${trimmed}${path}/oauth2/callback/${PLATFORM_SSO_PROVIDER_ID}`;
|
|
6683
|
-
}
|
|
6684
|
-
async function seedPlatformSsoClient(opts) {
|
|
6685
|
-
const { ql, environmentId, hostname, baseSecret, logger, throwOnError } = opts;
|
|
6686
|
-
if (!baseSecret) {
|
|
6687
|
-
logger?.warn?.("[platform-sso] OS_AUTH_SECRET not set \u2014 skipping client seed", { environmentId });
|
|
6688
|
-
return;
|
|
6689
|
-
}
|
|
6690
|
-
const clientId = derivePlatformSsoClientId(environmentId);
|
|
6691
|
-
const clientSecretPlaintext = derivePlatformSsoClientSecret(baseSecret, environmentId);
|
|
6692
|
-
const clientSecretStored = hashPlatformSsoClientSecret(clientSecretPlaintext);
|
|
6693
|
-
const desiredRedirect = hostname ? buildPlatformSsoRedirectUri(hostname) : null;
|
|
6694
|
-
let existing = null;
|
|
6695
|
-
try {
|
|
6696
|
-
const rows = await ql.find("sys_oauth_application", {
|
|
6697
|
-
where: { client_id: clientId },
|
|
6698
|
-
limit: 1
|
|
6699
|
-
}, { context: { isSystem: true } });
|
|
6700
|
-
const list = Array.isArray(rows) ? rows : Array.isArray(rows?.records) ? rows.records : [];
|
|
6701
|
-
existing = list[0] ?? null;
|
|
6702
|
-
} catch (err) {
|
|
6703
|
-
logger?.warn?.("[platform-sso] sys_oauth_application read failed \u2014 skipping seed", {
|
|
6704
|
-
environmentId,
|
|
6705
|
-
error: err?.message
|
|
6706
|
-
});
|
|
6707
|
-
return;
|
|
6708
|
-
}
|
|
6709
|
-
const nowIso = (/* @__PURE__ */ new Date()).toISOString();
|
|
6710
|
-
if (!existing) {
|
|
6711
|
-
const redirects = desiredRedirect ? [desiredRedirect] : [];
|
|
6712
|
-
try {
|
|
6713
|
-
await ql.insert("sys_oauth_application", {
|
|
6714
|
-
id: `oauthc_${environmentId}`,
|
|
6715
|
-
name: `Project ${environmentId}`,
|
|
6716
|
-
client_id: clientId,
|
|
6717
|
-
client_secret: clientSecretStored,
|
|
6718
|
-
type: "web",
|
|
6719
|
-
redirect_uris: JSON.stringify(redirects),
|
|
6720
|
-
grant_types: JSON.stringify(["authorization_code", "refresh_token"]),
|
|
6721
|
-
response_types: JSON.stringify(["code"]),
|
|
6722
|
-
scopes: JSON.stringify(["openid", "email", "profile"]),
|
|
6723
|
-
token_endpoint_auth_method: "client_secret_basic",
|
|
6724
|
-
require_pkce: false,
|
|
6725
|
-
skip_consent: true,
|
|
6726
|
-
disabled: false,
|
|
6727
|
-
subject_type: "public",
|
|
6728
|
-
created_at: nowIso,
|
|
6729
|
-
updated_at: nowIso
|
|
6730
|
-
}, { context: { isSystem: true } });
|
|
6731
|
-
logger?.info?.("[platform-sso] sys_oauth_application row created", { environmentId, clientId });
|
|
6732
|
-
} catch (err) {
|
|
6733
|
-
logger?.warn?.("[platform-sso] sys_oauth_application create failed", {
|
|
6734
|
-
environmentId,
|
|
6735
|
-
error: err?.message
|
|
6736
|
-
});
|
|
6737
|
-
if (throwOnError) throw err;
|
|
6738
|
-
}
|
|
6739
|
-
return;
|
|
6740
|
-
}
|
|
6741
|
-
let currentRedirects = [];
|
|
6742
|
-
try {
|
|
6743
|
-
const raw = existing.redirect_uris;
|
|
6744
|
-
const parsed = typeof raw === "string" ? JSON.parse(raw) : raw;
|
|
6745
|
-
if (Array.isArray(parsed)) currentRedirects = parsed.filter((s) => typeof s === "string");
|
|
6746
|
-
} catch {
|
|
6747
|
-
}
|
|
6748
|
-
const mergedRedirects = desiredRedirect && !currentRedirects.includes(desiredRedirect) ? [...currentRedirects, desiredRedirect] : currentRedirects;
|
|
6749
|
-
const repairPatch = {
|
|
6750
|
-
name: existing.name || `Project ${environmentId}`,
|
|
6751
|
-
client_secret: clientSecretStored,
|
|
6752
|
-
type: existing.type || "web",
|
|
6753
|
-
redirect_uris: JSON.stringify(mergedRedirects),
|
|
6754
|
-
grant_types: JSON.stringify(["authorization_code", "refresh_token"]),
|
|
6755
|
-
response_types: JSON.stringify(["code"]),
|
|
6756
|
-
scopes: JSON.stringify(["openid", "email", "profile"]),
|
|
6757
|
-
token_endpoint_auth_method: "client_secret_basic",
|
|
6758
|
-
require_pkce: false,
|
|
6759
|
-
skip_consent: true,
|
|
6760
|
-
disabled: false,
|
|
6761
|
-
subject_type: "public",
|
|
6762
|
-
updated_at: nowIso
|
|
6763
|
-
};
|
|
6764
|
-
try {
|
|
6765
|
-
await ql.update(
|
|
6766
|
-
"sys_oauth_application",
|
|
6767
|
-
repairPatch,
|
|
6768
|
-
{ where: { id: existing.id } },
|
|
6769
|
-
{ context: { isSystem: true } }
|
|
6770
|
-
);
|
|
6771
|
-
logger?.info?.("[platform-sso] sys_oauth_application repaired", {
|
|
6772
|
-
environmentId,
|
|
6773
|
-
clientId,
|
|
6774
|
-
redirect_uris: mergedRedirects
|
|
6775
|
-
});
|
|
6776
|
-
} catch (err) {
|
|
6777
|
-
logger?.warn?.("[platform-sso] sys_oauth_application repair failed", {
|
|
6778
|
-
environmentId,
|
|
6779
|
-
error: err?.message
|
|
6780
|
-
});
|
|
6781
|
-
if (throwOnError) throw err;
|
|
6782
|
-
}
|
|
6783
|
-
}
|
|
6784
|
-
async function backfillPlatformSsoClients(opts) {
|
|
6785
|
-
const { ql, baseSecret, logger, limit = 1e3 } = opts;
|
|
6786
|
-
if (!baseSecret) {
|
|
6787
|
-
logger?.warn?.("[platform-sso] backfill skipped \u2014 OS_AUTH_SECRET not set");
|
|
6788
|
-
return { scanned: 0, seeded: 0, alreadyExisted: 0, failures: [] };
|
|
6789
|
-
}
|
|
6790
|
-
let projects = [];
|
|
6791
|
-
try {
|
|
6792
|
-
const rows = await ql.find("sys_environment", {
|
|
6793
|
-
limit,
|
|
6794
|
-
fields: ["id", "hostname", "status"]
|
|
6795
|
-
}, { context: { isSystem: true } });
|
|
6796
|
-
projects = Array.isArray(rows) ? rows : Array.isArray(rows?.records) ? rows.records : [];
|
|
6797
|
-
} catch (err) {
|
|
6798
|
-
logger?.warn?.("[platform-sso] backfill: sys_environment read failed", {
|
|
6799
|
-
error: err?.message
|
|
6800
|
-
});
|
|
6801
|
-
return { scanned: 0, seeded: 0, alreadyExisted: 0, failures: [{ environmentId: "<scan>", error: err?.message ?? String(err) }] };
|
|
6802
|
-
}
|
|
6803
|
-
let seeded = 0;
|
|
6804
|
-
let alreadyExisted = 0;
|
|
6805
|
-
const failures = [];
|
|
6806
|
-
for (const p of projects) {
|
|
6807
|
-
if (!p?.id) continue;
|
|
6808
|
-
const before = await (async () => {
|
|
6809
|
-
try {
|
|
6810
|
-
const r = await ql.find("sys_oauth_application", {
|
|
6811
|
-
where: { client_id: derivePlatformSsoClientId(p.id) },
|
|
6812
|
-
limit: 1
|
|
6813
|
-
}, { context: { isSystem: true } });
|
|
6814
|
-
const list = Array.isArray(r) ? r : Array.isArray(r?.records) ? r.records : [];
|
|
6815
|
-
return list[0] ?? null;
|
|
6816
|
-
} catch {
|
|
6817
|
-
return null;
|
|
6818
|
-
}
|
|
6819
|
-
})();
|
|
6820
|
-
try {
|
|
6821
|
-
await seedPlatformSsoClient({ ql, environmentId: p.id, hostname: p.hostname, baseSecret, logger, throwOnError: true });
|
|
6822
|
-
if (before) alreadyExisted++;
|
|
6823
|
-
else {
|
|
6824
|
-
const after = await (async () => {
|
|
6825
|
-
try {
|
|
6826
|
-
const r = await ql.find("sys_oauth_application", {
|
|
6827
|
-
where: { client_id: derivePlatformSsoClientId(p.id) },
|
|
6828
|
-
limit: 1
|
|
6829
|
-
}, { context: { isSystem: true } });
|
|
6830
|
-
const list = Array.isArray(r) ? r : Array.isArray(r?.records) ? r.records : [];
|
|
6831
|
-
return list[0] ?? null;
|
|
6832
|
-
} catch (err) {
|
|
6833
|
-
return { _readErr: err?.message };
|
|
6834
|
-
}
|
|
6835
|
-
})();
|
|
6836
|
-
if (after && !after._readErr) seeded++;
|
|
6837
|
-
else failures.push({ environmentId: p.id, error: `post-insert read returned ${after ? JSON.stringify(after) : "null"}` });
|
|
6838
|
-
}
|
|
6839
|
-
} catch (err) {
|
|
6840
|
-
failures.push({ environmentId: p.id, error: err?.message ?? String(err) });
|
|
6841
|
-
}
|
|
6842
|
-
}
|
|
6843
|
-
logger?.info?.("[platform-sso] backfill complete", { scanned: projects.length, seeded, alreadyExisted, failures: failures.length });
|
|
6844
|
-
return { scanned: projects.length, seeded, alreadyExisted, failures };
|
|
6845
|
-
}
|
|
6846
|
-
|
|
6847
|
-
// src/cloud/artifact-kernel-factory.ts
|
|
6848
|
-
function deriveProjectAuthSecret(baseSecret, environmentId) {
|
|
6849
|
-
return createHmac2("sha256", baseSecret).update(`project:${environmentId}`).digest("hex");
|
|
6850
|
-
}
|
|
6851
|
-
var ArtifactKernelFactory = class {
|
|
6852
|
-
constructor(config) {
|
|
6853
|
-
this.client = config.client;
|
|
6854
|
-
this.envRegistry = config.envRegistry;
|
|
6855
|
-
this.logger = config.logger ?? console;
|
|
6856
|
-
this.kernelConfig = config.kernelConfig;
|
|
6857
|
-
this.authBaseSecret = (config.authBaseSecret ?? readEnvWithDeprecation3("OS_AUTH_SECRET", ["AUTH_SECRET", "BETTER_AUTH_SECRET"]) ?? "").trim();
|
|
6858
|
-
}
|
|
6859
|
-
async create(environmentId) {
|
|
6860
|
-
let cached = this.envRegistry.peekById(environmentId);
|
|
6861
|
-
if (!cached) {
|
|
6862
|
-
const driver2 = await this.envRegistry.resolveById(environmentId);
|
|
6863
|
-
if (!driver2) {
|
|
6864
|
-
throw new Error(`[ArtifactKernelFactory] Could not resolve driver for project '${environmentId}'`);
|
|
6865
|
-
}
|
|
6866
|
-
cached = this.envRegistry.peekById(environmentId);
|
|
6867
|
-
if (!cached) {
|
|
6868
|
-
throw new Error(`[ArtifactKernelFactory] envRegistry returned a driver but no cached entry for '${environmentId}'`);
|
|
6869
|
-
}
|
|
6870
|
-
}
|
|
6871
|
-
const driver = cached.driver;
|
|
6872
|
-
const project = cached.project;
|
|
6873
|
-
const artifact = await this.client.fetchArtifact(environmentId);
|
|
6874
|
-
if (!artifact) {
|
|
6875
|
-
throw new Error(`[ArtifactKernelFactory] Artifact not available for project '${environmentId}'`);
|
|
6876
|
-
}
|
|
6877
|
-
const { ObjectQLPlugin } = await import("@objectstack/objectql");
|
|
6878
|
-
const { MetadataPlugin } = await import("@objectstack/metadata");
|
|
6879
|
-
const kernel = new ObjectKernel3(this.kernelConfig);
|
|
6880
|
-
await kernel.use(new DriverPlugin(driver, { datasourceName: "cloud" }));
|
|
6881
|
-
await kernel.use(new ObjectQLPlugin({ environmentId, skipSchemaSync: false }));
|
|
6882
|
-
await kernel.use(new MetadataPlugin({
|
|
6883
|
-
watch: false,
|
|
6884
|
-
environmentId,
|
|
6885
|
-
organizationId: project.organization_id,
|
|
6886
|
-
// ADR-0005: customization overlays (user-created views, dashboards,
|
|
6887
|
-
// edited objects, ...) are persisted by
|
|
6888
|
-
// ObjectStackProtocolImplementation.saveMetaItem on whichever
|
|
6889
|
-
// engine the protocol is attached to. For per-project kernels that
|
|
6890
|
-
// means the project's own DB, so the sys_metadata + history tables
|
|
6891
|
-
// MUST be provisioned here. The previous `false` setting caused
|
|
6892
|
-
// "no such table: sys_metadata" errors on any PUT /api/v1/meta/*
|
|
6893
|
-
// call (e.g. Studio "Create View") against a project deployment.
|
|
6894
|
-
registerSystemObjects: true
|
|
6895
|
-
}));
|
|
6896
|
-
if (this.authBaseSecret) {
|
|
6897
|
-
try {
|
|
6898
|
-
const { AuthPlugin } = await import("@objectstack/plugin-auth");
|
|
6899
|
-
const projectSecret = deriveProjectAuthSecret(this.authBaseSecret, environmentId);
|
|
6900
|
-
const baseUrl = project.hostname ? project.hostname.startsWith("http") ? project.hostname : /(\.|^)localhost(:\d+)?$/i.test(project.hostname) ? (() => {
|
|
6901
|
-
const runtimePort = (process.env.OS_RUNTIME_PORT ?? "").trim();
|
|
6902
|
-
const hasPort = /:\d+$/.test(project.hostname);
|
|
6903
|
-
const hostWithPort = hasPort || !runtimePort ? project.hostname : `${project.hostname}:${runtimePort}`;
|
|
6904
|
-
return `http://${hostWithPort}`;
|
|
6905
|
-
})() : `https://${project.hostname}` : void 0;
|
|
6906
|
-
const trustedOriginsList = [];
|
|
6907
|
-
if (baseUrl) trustedOriginsList.push(baseUrl);
|
|
6908
|
-
const platformOrigins = (process.env.OS_TRUSTED_ORIGINS ?? "").split(",").map((s) => s.trim()).filter(Boolean);
|
|
6909
|
-
for (const o of platformOrigins) {
|
|
6910
|
-
if (!trustedOriginsList.includes(o)) trustedOriginsList.push(o);
|
|
6911
|
-
}
|
|
6912
|
-
const rootDomain = (process.env.OS_ROOT_DOMAIN ?? "").trim().replace(/^https?:\/\//, "");
|
|
6913
|
-
if (rootDomain) {
|
|
6914
|
-
const wildcard = `https://*.${rootDomain}`;
|
|
6915
|
-
if (!trustedOriginsList.includes(wildcard)) trustedOriginsList.push(wildcard);
|
|
6916
|
-
}
|
|
6917
|
-
if (project.hostname) {
|
|
6918
|
-
const bareHost = project.hostname.replace(/^https?:\/\//, "");
|
|
6919
|
-
if (bareHost.endsWith(".localhost") || bareHost === "localhost") {
|
|
6920
|
-
trustedOriginsList.push(`http://${bareHost}`);
|
|
6921
|
-
trustedOriginsList.push(`http://${bareHost}:*`);
|
|
6922
|
-
trustedOriginsList.push(`https://${bareHost}:*`);
|
|
6923
|
-
}
|
|
6924
|
-
}
|
|
6925
|
-
const platformSsoEnabled = String(
|
|
6926
|
-
process.env.OS_PLATFORM_SSO ?? "true"
|
|
6927
|
-
).toLowerCase() !== "false";
|
|
6928
|
-
const cloudBaseUrl = (process.env.OS_CLOUD_URL ?? "").trim().replace(/\/+$/, "");
|
|
6929
|
-
const oidcProviders = platformSsoEnabled && cloudBaseUrl && /^https?:\/\//.test(cloudBaseUrl) ? [{
|
|
6930
|
-
providerId: PLATFORM_SSO_PROVIDER_ID,
|
|
6931
|
-
name: "ObjectStack",
|
|
6932
|
-
discoveryUrl: `${cloudBaseUrl}/.well-known/openid-configuration`,
|
|
6933
|
-
clientId: derivePlatformSsoClientId(environmentId),
|
|
6934
|
-
clientSecret: derivePlatformSsoClientSecret(this.authBaseSecret, environmentId),
|
|
6935
|
-
scopes: ["openid", "email", "profile"]
|
|
6936
|
-
}] : void 0;
|
|
6937
|
-
await kernel.use(new AuthPlugin({
|
|
6938
|
-
secret: projectSecret,
|
|
6939
|
-
baseUrl,
|
|
6940
|
-
// Project kernel has no http-server (host owns it). The
|
|
6941
|
-
// dispatcher's handleAuth path resolves `auth` via
|
|
6942
|
-
// getService and invokes the handler directly — route
|
|
6943
|
-
// registration is unnecessary and would warn.
|
|
6944
|
-
registerRoutes: false,
|
|
6945
|
-
// Identity tables live in the project's own DB — keep
|
|
6946
|
-
// sys_user/sys_session local to this kernel.
|
|
6947
|
-
manifestDatasource: "default",
|
|
6948
|
-
// Cookie scope: default to the project's own host. We
|
|
6949
|
-
// intentionally do NOT pass crossSubDomainCookies here
|
|
6950
|
-
// so cookies stay isolated per project subdomain.
|
|
6951
|
-
trustedOrigins: trustedOriginsList.length ? trustedOriginsList : void 0,
|
|
6952
|
-
...oidcProviders ? { oidcProviders } : {}
|
|
6953
|
-
}));
|
|
6954
|
-
if (oidcProviders) {
|
|
6955
|
-
this.logger.info?.("[ArtifactKernelFactory] platform SSO wired", {
|
|
6956
|
-
environmentId,
|
|
6957
|
-
cloudBaseUrl
|
|
6958
|
-
});
|
|
6959
|
-
}
|
|
6960
|
-
} catch (err) {
|
|
6961
|
-
this.logger.warn?.("[ArtifactKernelFactory] AuthPlugin not registered", {
|
|
6962
|
-
environmentId,
|
|
6963
|
-
error: err?.message
|
|
6964
|
-
});
|
|
6965
|
-
}
|
|
6966
|
-
} else {
|
|
6967
|
-
this.logger.warn?.("[ArtifactKernelFactory] OS_AUTH_SECRET not set \u2014 per-project AuthPlugin skipped (auth endpoints will return 404)", { environmentId });
|
|
6968
|
-
}
|
|
6969
|
-
try {
|
|
6970
|
-
const multiTenant = String(readEnvWithDeprecation3("OS_MULTI_ORG_ENABLED", "OS_MULTI_TENANT") ?? "false").toLowerCase() !== "false";
|
|
6971
|
-
if (multiTenant) {
|
|
6972
|
-
try {
|
|
6973
|
-
const { OrgScopingPlugin } = await import("@objectstack/plugin-org-scoping");
|
|
6974
|
-
await kernel.use(new OrgScopingPlugin());
|
|
6975
|
-
} catch (err) {
|
|
6976
|
-
this.logger.warn?.("[ArtifactKernelFactory] OrgScopingPlugin not registered (multi-tenant disabled)", {
|
|
6977
|
-
environmentId,
|
|
6978
|
-
error: err?.message
|
|
6979
|
-
});
|
|
6980
|
-
}
|
|
6981
|
-
}
|
|
6982
|
-
const { SecurityPlugin } = await import("@objectstack/plugin-security");
|
|
6983
|
-
await kernel.use(new SecurityPlugin());
|
|
6984
|
-
} catch (err) {
|
|
6985
|
-
this.logger.warn?.("[ArtifactKernelFactory] SecurityPlugin not registered", {
|
|
6986
|
-
environmentId,
|
|
6987
|
-
error: err?.message
|
|
6988
|
-
});
|
|
6989
|
-
}
|
|
6990
|
-
const projectName = project.hostname ?? environmentId;
|
|
6991
|
-
const artifactAny = artifact;
|
|
6992
|
-
const topLevelManifest = artifactAny?.manifest && typeof artifactAny.manifest === "object" ? artifactAny.manifest : null;
|
|
6993
|
-
const topLevelFunctions = Array.isArray(artifactAny?.functions) ? artifactAny.functions : [];
|
|
6994
|
-
const bundle = {
|
|
6995
|
-
...artifact.metadata ?? {},
|
|
6996
|
-
...topLevelManifest ? { manifest: topLevelManifest } : {},
|
|
6997
|
-
functions: topLevelFunctions
|
|
6998
|
-
};
|
|
6999
|
-
const sys = bundle.manifest ?? bundle;
|
|
7000
|
-
const packageId = sys?.packageId ?? sys?.package_id ?? bundle?.packageId;
|
|
7001
|
-
const i18nCfg = bundle?.i18n ?? sys?.i18n ?? {};
|
|
7002
|
-
const trArr = Array.isArray(bundle?.translations) ? bundle.translations : Array.isArray(sys?.translations) ? sys.translations : [];
|
|
7003
|
-
try {
|
|
7004
|
-
const { I18nServicePlugin } = await import("@objectstack/service-i18n");
|
|
7005
|
-
await kernel.use(new I18nServicePlugin({
|
|
7006
|
-
defaultLocale: i18nCfg.defaultLocale,
|
|
7007
|
-
fallbackLocale: i18nCfg.fallbackLocale ?? i18nCfg.defaultLocale ?? "en",
|
|
7008
|
-
// Routes are dispatched by HttpDispatcher.handleI18n via
|
|
7009
|
-
// kernel.getService('i18n'); the host worker owns the
|
|
7010
|
-
// HTTP server. Skip self-registration to avoid warnings.
|
|
7011
|
-
registerRoutes: false
|
|
7012
|
-
}));
|
|
7013
|
-
console.warn(
|
|
7014
|
-
`[ArtifactKernelFactory] I18nServicePlugin registered (project=${environmentId}, translations=${trArr.length}, defaultLocale=${i18nCfg.defaultLocale ?? "en"})`
|
|
7015
|
-
);
|
|
7016
|
-
} catch (err) {
|
|
7017
|
-
this.logger.warn?.("[ArtifactKernelFactory] I18nServicePlugin not registered", {
|
|
7018
|
-
environmentId,
|
|
7019
|
-
error: err?.message
|
|
7020
|
-
});
|
|
7021
|
-
}
|
|
7022
|
-
const requiresRaw = (Array.isArray(bundle?.requires) ? bundle.requires : null) ?? (Array.isArray(sys?.requires) ? sys.requires : null) ?? [];
|
|
7023
|
-
const requires = requiresRaw.filter((x) => typeof x === "string" && x.length > 0);
|
|
7024
|
-
if (requires.length > 0) {
|
|
7025
|
-
const installed = await loadCapabilities({
|
|
7026
|
-
kernel,
|
|
7027
|
-
requires,
|
|
7028
|
-
bundle: { ...bundle ?? {}, ...sys ?? {} },
|
|
7029
|
-
logger: this.logger,
|
|
7030
|
-
environmentId
|
|
7031
|
-
});
|
|
7032
|
-
this.logger.info?.("[ArtifactKernelFactory] capabilities loaded", {
|
|
7033
|
-
environmentId,
|
|
7034
|
-
requires,
|
|
7035
|
-
installed
|
|
7036
|
-
});
|
|
7037
|
-
}
|
|
7038
|
-
await kernel.use(new AppPlugin(bundle, {
|
|
7039
|
-
environmentId,
|
|
7040
|
-
organizationId: project.organization_id ?? "",
|
|
7041
|
-
projectName,
|
|
7042
|
-
packageId,
|
|
7043
|
-
source: packageId ? "package" : "user"
|
|
7044
|
-
}));
|
|
7045
|
-
await kernel.bootstrap();
|
|
7046
|
-
try {
|
|
7047
|
-
const projMeta = typeof project?.metadata === "string" ? JSON.parse(project.metadata) : project?.metadata ?? {};
|
|
7048
|
-
const ownerSeed = projMeta?.ownerSeed;
|
|
7049
|
-
const orgSeed = projMeta?.orgSeed;
|
|
7050
|
-
if (orgSeed?.id && orgSeed?.name) {
|
|
7051
|
-
try {
|
|
7052
|
-
const { seedProjectOrganization: seedProjectOrganization2 } = await Promise.resolve().then(() => (init_environment_org_seed(), environment_org_seed_exports));
|
|
7053
|
-
await seedProjectOrganization2(kernel, orgSeed, this.logger);
|
|
7054
|
-
} catch (e) {
|
|
7055
|
-
this.logger.warn?.("[ArtifactKernelFactory] orgSeed threw", {
|
|
7056
|
-
environmentId,
|
|
7057
|
-
error: e?.message
|
|
7058
|
-
});
|
|
7059
|
-
}
|
|
7060
|
-
}
|
|
7061
|
-
if (ownerSeed?.userId && ownerSeed?.email) {
|
|
7062
|
-
try {
|
|
7063
|
-
const { seedProjectOwner: seedProjectOwner2 } = await Promise.resolve().then(() => (init_environment_owner_seed(), environment_owner_seed_exports));
|
|
7064
|
-
await seedProjectOwner2(kernel, ownerSeed, this.logger);
|
|
7065
|
-
} catch (e) {
|
|
7066
|
-
this.logger.warn?.("[ArtifactKernelFactory] ownerSeed threw", {
|
|
7067
|
-
environmentId,
|
|
7068
|
-
error: e?.message
|
|
7069
|
-
});
|
|
7070
|
-
}
|
|
7071
|
-
if (orgSeed?.id) {
|
|
7072
|
-
try {
|
|
7073
|
-
const { seedProjectMember: seedProjectMember2 } = await Promise.resolve().then(() => (init_environment_org_seed(), environment_org_seed_exports));
|
|
7074
|
-
await seedProjectMember2(
|
|
7075
|
-
kernel,
|
|
7076
|
-
{ userId: ownerSeed.userId, organizationId: orgSeed.id, role: "owner" },
|
|
7077
|
-
this.logger
|
|
7078
|
-
);
|
|
7079
|
-
} catch (e) {
|
|
7080
|
-
this.logger.warn?.("[ArtifactKernelFactory] memberSeed threw", {
|
|
7081
|
-
environmentId,
|
|
7082
|
-
error: e?.message
|
|
7083
|
-
});
|
|
7084
|
-
}
|
|
7085
|
-
}
|
|
7086
|
-
}
|
|
7087
|
-
} catch (err) {
|
|
7088
|
-
this.logger.warn?.("[ArtifactKernelFactory] owner/org seed skipped", {
|
|
7089
|
-
environmentId,
|
|
7090
|
-
error: err?.message
|
|
7091
|
-
});
|
|
7092
|
-
}
|
|
7093
|
-
try {
|
|
7094
|
-
const datasetsNow = (() => {
|
|
7095
|
-
try {
|
|
7096
|
-
return kernel.getService?.("seed-datasets");
|
|
7097
|
-
} catch {
|
|
7098
|
-
return void 0;
|
|
7099
|
-
}
|
|
7100
|
-
})();
|
|
7101
|
-
const replayer = (() => {
|
|
7102
|
-
try {
|
|
7103
|
-
return kernel.getService?.("seed-replayer");
|
|
7104
|
-
} catch {
|
|
7105
|
-
return void 0;
|
|
7106
|
-
}
|
|
7107
|
-
})();
|
|
7108
|
-
if (Array.isArray(datasetsNow) && datasetsNow.length > 0 && typeof replayer === "function") {
|
|
7109
|
-
const projMetaRaw = project?.metadata;
|
|
7110
|
-
const projMeta = typeof projMetaRaw === "string" ? (() => {
|
|
7111
|
-
try {
|
|
7112
|
-
return JSON.parse(projMetaRaw);
|
|
7113
|
-
} catch {
|
|
7114
|
-
return {};
|
|
7115
|
-
}
|
|
7116
|
-
})() : projMetaRaw ?? {};
|
|
7117
|
-
let primaryOrgId = projMeta?.orgSeed?.id;
|
|
7118
|
-
if (!primaryOrgId) {
|
|
7119
|
-
try {
|
|
7120
|
-
const ql = kernel.getService?.("objectql");
|
|
7121
|
-
if (ql?.find) {
|
|
7122
|
-
const rows = await ql.find("sys_organization", { limit: 5, orderBy: [{ field: "created_at", direction: "asc" }] });
|
|
7123
|
-
const list = Array.isArray(rows) ? rows : rows?.value ?? rows?.records ?? [];
|
|
7124
|
-
if (Array.isArray(list) && list.length > 0 && list[0]?.id) {
|
|
7125
|
-
primaryOrgId = String(list[0].id);
|
|
7126
|
-
}
|
|
7127
|
-
}
|
|
7128
|
-
} catch {
|
|
7129
|
-
}
|
|
7130
|
-
}
|
|
7131
|
-
if (primaryOrgId) {
|
|
7132
|
-
try {
|
|
7133
|
-
const summary = await replayer(primaryOrgId);
|
|
7134
|
-
const inserted = summary?.inserted ?? 0;
|
|
7135
|
-
const updated = summary?.updated ?? 0;
|
|
7136
|
-
const errs = summary?.errors?.length ?? 0;
|
|
7137
|
-
if (inserted > 0 || updated > 0 || errs > 0) {
|
|
7138
|
-
this.logger.info?.("[ArtifactKernelFactory] post-bootstrap seed replay", {
|
|
7139
|
-
environmentId,
|
|
7140
|
-
organizationId: primaryOrgId,
|
|
7141
|
-
datasets: datasetsNow.length,
|
|
7142
|
-
inserted,
|
|
7143
|
-
updated,
|
|
7144
|
-
errors: errs
|
|
7145
|
-
});
|
|
7146
|
-
}
|
|
7147
|
-
} catch (e) {
|
|
7148
|
-
this.logger.warn?.("[ArtifactKernelFactory] post-bootstrap seed replay failed", {
|
|
7149
|
-
environmentId,
|
|
7150
|
-
organizationId: primaryOrgId,
|
|
7151
|
-
error: e?.message
|
|
7152
|
-
});
|
|
7153
|
-
}
|
|
7154
|
-
}
|
|
7155
|
-
}
|
|
7156
|
-
} catch (err) {
|
|
7157
|
-
this.logger.warn?.("[ArtifactKernelFactory] post-bootstrap seed step threw", {
|
|
7158
|
-
environmentId,
|
|
7159
|
-
error: err?.message
|
|
7160
|
-
});
|
|
7161
|
-
}
|
|
7162
|
-
let i18nSvc = null;
|
|
7163
|
-
try {
|
|
7164
|
-
i18nSvc = kernel.getService?.("i18n");
|
|
7165
|
-
} catch {
|
|
7166
|
-
i18nSvc = null;
|
|
7167
|
-
}
|
|
7168
|
-
try {
|
|
7169
|
-
if (i18nSvc && typeof i18nSvc.loadTranslations === "function") {
|
|
7170
|
-
if (i18nCfg.defaultLocale && typeof i18nSvc.setDefaultLocale === "function") {
|
|
7171
|
-
i18nSvc.setDefaultLocale(i18nCfg.defaultLocale);
|
|
7172
|
-
}
|
|
7173
|
-
let loaded = 0;
|
|
7174
|
-
for (const tbundle of trArr) {
|
|
7175
|
-
if (!tbundle || typeof tbundle !== "object") continue;
|
|
7176
|
-
for (const [locale, data] of Object.entries(tbundle)) {
|
|
7177
|
-
if (data && typeof data === "object") {
|
|
7178
|
-
try {
|
|
7179
|
-
i18nSvc.loadTranslations(locale, data);
|
|
7180
|
-
loaded++;
|
|
7181
|
-
} catch (err) {
|
|
7182
|
-
this.logger.warn?.("[ArtifactKernelFactory] i18n loadTranslations failed", {
|
|
7183
|
-
environmentId,
|
|
7184
|
-
locale,
|
|
7185
|
-
error: err?.message
|
|
7186
|
-
});
|
|
7187
|
-
}
|
|
7188
|
-
}
|
|
7189
|
-
}
|
|
7190
|
-
}
|
|
7191
|
-
if (loaded > 0) {
|
|
7192
|
-
this.logger.info?.("[ArtifactKernelFactory] i18n direct-load complete", {
|
|
7193
|
-
environmentId,
|
|
7194
|
-
locales: loaded,
|
|
7195
|
-
bundles: trArr.length
|
|
7196
|
-
});
|
|
7197
|
-
}
|
|
7198
|
-
}
|
|
7199
|
-
} catch (err) {
|
|
7200
|
-
this.logger.warn?.("[ArtifactKernelFactory] i18n direct-load failed", {
|
|
7201
|
-
environmentId,
|
|
7202
|
-
error: err?.message
|
|
7203
|
-
});
|
|
7204
|
-
}
|
|
7205
|
-
this.logger.info?.("[ArtifactKernelFactory] kernel ready", {
|
|
7206
|
-
environmentId,
|
|
7207
|
-
commitId: artifact.commitId,
|
|
7208
|
-
checksum: artifact.checksum,
|
|
7209
|
-
authEnabled: Boolean(this.authBaseSecret)
|
|
7210
|
-
});
|
|
7211
|
-
return kernel;
|
|
7212
|
-
}
|
|
7213
|
-
};
|
|
7214
|
-
|
|
7215
|
-
// src/cloud/auth-proxy-plugin.ts
|
|
7216
|
-
import { createHmac as createHmac3, randomUUID as randomUUID2 } from "crypto";
|
|
7217
|
-
var AUTH_PREFIX = "/api/v1/auth";
|
|
7218
|
-
function signSessionCookieValue(rawToken, secret) {
|
|
7219
|
-
const signature = createHmac3("sha256", secret).update(rawToken).digest("base64");
|
|
7220
|
-
return encodeURIComponent(`${rawToken}.${signature}`);
|
|
7221
|
-
}
|
|
7222
|
-
function buildSetCookieHeader(name, encodedValue, attrs, maxAgeSec) {
|
|
7223
|
-
const parts = [`${name}=${encodedValue}`];
|
|
7224
|
-
const a = attrs ?? {};
|
|
7225
|
-
if (a.path) parts.push(`Path=${a.path}`);
|
|
7226
|
-
else parts.push("Path=/");
|
|
7227
|
-
if (Number.isFinite(maxAgeSec) && maxAgeSec > 0) parts.push(`Max-Age=${Math.floor(maxAgeSec)}`);
|
|
7228
|
-
if (a.domain) parts.push(`Domain=${a.domain}`);
|
|
7229
|
-
if (a.sameSite) {
|
|
7230
|
-
const ss = String(a.sameSite);
|
|
7231
|
-
parts.push(`SameSite=${ss.charAt(0).toUpperCase() + ss.slice(1)}`);
|
|
7232
|
-
} else {
|
|
7233
|
-
parts.push("SameSite=Lax");
|
|
7234
|
-
}
|
|
7235
|
-
if (a.secure) parts.push("Secure");
|
|
7236
|
-
if (a.httpOnly !== false) parts.push("HttpOnly");
|
|
7237
|
-
if (a.partitioned) parts.push("Partitioned");
|
|
7238
|
-
return parts.join("; ");
|
|
7239
|
-
}
|
|
7240
|
-
function pickHandler(svc) {
|
|
7241
|
-
if (!svc) return void 0;
|
|
7242
|
-
if (typeof svc.handleRequest === "function") return svc.handleRequest.bind(svc);
|
|
7243
|
-
if (typeof svc.handler === "function") return svc.handler.bind(svc);
|
|
7244
|
-
if (svc.api && typeof svc.api.handler === "function") return svc.api.handler.bind(svc.api);
|
|
7245
|
-
if (svc.auth && typeof svc.auth.handler === "function") return svc.auth.handler.bind(svc.auth);
|
|
7246
|
-
return void 0;
|
|
7247
|
-
}
|
|
7248
|
-
async function resolveAuthHandler(svc) {
|
|
7249
|
-
const direct = pickHandler(svc);
|
|
7250
|
-
if (direct) return direct;
|
|
7251
|
-
if (typeof svc?.getApi === "function") {
|
|
7252
|
-
try {
|
|
7253
|
-
const api = await svc.getApi();
|
|
7254
|
-
return pickHandler(api) ?? pickHandler({ api });
|
|
7255
|
-
} catch {
|
|
7256
|
-
return void 0;
|
|
7257
|
-
}
|
|
7258
|
-
}
|
|
7259
|
-
return void 0;
|
|
7260
|
-
}
|
|
7261
|
-
var AuthProxyPlugin = class {
|
|
7262
|
-
constructor() {
|
|
7263
|
-
this.name = "com.objectstack.runtime.auth-proxy";
|
|
7264
|
-
this.version = "1.0.0";
|
|
7265
|
-
this.init = async (_ctx) => {
|
|
7266
|
-
};
|
|
7267
|
-
this.start = async (ctx) => {
|
|
7268
|
-
ctx.hook("kernel:ready", async () => {
|
|
7269
|
-
let httpServer;
|
|
7270
|
-
try {
|
|
7271
|
-
httpServer = ctx.getService("http-server");
|
|
7272
|
-
} catch {
|
|
7273
|
-
ctx.logger?.warn?.("[AuthProxyPlugin] http-server not available \u2014 auth routes not mounted");
|
|
7274
|
-
return;
|
|
7275
|
-
}
|
|
7276
|
-
if (!httpServer || typeof httpServer.getRawApp !== "function") {
|
|
7277
|
-
ctx.logger?.warn?.("[AuthProxyPlugin] http-server missing getRawApp() \u2014 auth routes not mounted");
|
|
7278
|
-
return;
|
|
7279
|
-
}
|
|
7280
|
-
const rawApp = httpServer.getRawApp();
|
|
7281
|
-
const kernelManager = ctx.getService("kernel-manager");
|
|
7282
|
-
const envRegistry = ctx.getService("env-registry");
|
|
7283
|
-
const handler = async (c) => {
|
|
7284
|
-
try {
|
|
7285
|
-
const url = new URL(c.req.url);
|
|
7286
|
-
const host = url.hostname;
|
|
7287
|
-
let environmentId;
|
|
7288
|
-
try {
|
|
7289
|
-
const env = await envRegistry.resolveByHostname(host);
|
|
7290
|
-
environmentId = env?.environmentId;
|
|
7291
|
-
} catch {
|
|
7292
|
-
}
|
|
7293
|
-
if (!environmentId) {
|
|
7294
|
-
return c.json({ error: "project_not_found", host }, 404);
|
|
7295
|
-
}
|
|
7296
|
-
const projectKernel = await kernelManager.getOrCreate(environmentId);
|
|
7297
|
-
let authSvc;
|
|
7298
|
-
try {
|
|
7299
|
-
authSvc = await projectKernel.getServiceAsync?.("auth");
|
|
7300
|
-
} catch {
|
|
7301
|
-
authSvc = void 0;
|
|
7302
|
-
}
|
|
7303
|
-
if (!authSvc) {
|
|
7304
|
-
try {
|
|
7305
|
-
authSvc = projectKernel.getService?.("auth");
|
|
7306
|
-
} catch {
|
|
7307
|
-
}
|
|
7308
|
-
}
|
|
7309
|
-
const subPath = url.pathname.startsWith(AUTH_PREFIX + "/") ? url.pathname.substring(AUTH_PREFIX.length + 1) : "";
|
|
7310
|
-
if (c.req.method === "GET" && (subPath === "config" || subPath === "bootstrap-status")) {
|
|
7311
|
-
if (subPath === "config") {
|
|
7312
|
-
try {
|
|
7313
|
-
const config = typeof authSvc?.getPublicConfig === "function" ? authSvc.getPublicConfig() : null;
|
|
7314
|
-
if (config) {
|
|
7315
|
-
return c.json({ success: true, data: config });
|
|
7316
|
-
}
|
|
7317
|
-
return c.json({ success: false, error: { code: "auth_config_unavailable", message: "AuthManager has no getPublicConfig()" } }, 503);
|
|
7318
|
-
} catch (e) {
|
|
7319
|
-
return c.json({ success: false, error: { code: "auth_config_error", message: String(e?.message ?? e) } }, 500);
|
|
7320
|
-
}
|
|
7321
|
-
}
|
|
7322
|
-
try {
|
|
7323
|
-
const dataEngine = typeof authSvc?.getDataEngine === "function" ? authSvc.getDataEngine() : null;
|
|
7324
|
-
if (!dataEngine || typeof dataEngine.count !== "function") {
|
|
7325
|
-
return c.json({ hasOwner: true });
|
|
7326
|
-
}
|
|
7327
|
-
const count = await dataEngine.count("sys_user", {});
|
|
7328
|
-
return c.json({ hasOwner: (count ?? 0) > 0 });
|
|
7329
|
-
} catch {
|
|
7330
|
-
return c.json({ hasOwner: true });
|
|
7331
|
-
}
|
|
7332
|
-
}
|
|
7333
|
-
if (c.req.method === "POST" && subPath === "sso-handoff-issue") {
|
|
7334
|
-
try {
|
|
7335
|
-
const expected = (process.env.OS_CLOUD_API_KEY ?? "").trim();
|
|
7336
|
-
if (!expected) {
|
|
7337
|
-
return c.json({ error: "sso_handoff_disabled", reason: "OS_CLOUD_API_KEY unset on env runtime" }, 503);
|
|
7338
|
-
}
|
|
7339
|
-
const authz = c.req.header("authorization") ?? "";
|
|
7340
|
-
const provided = authz.toLowerCase().startsWith("bearer ") ? authz.slice(7).trim() : "";
|
|
7341
|
-
if (!provided || provided !== expected) {
|
|
7342
|
-
return c.json({ error: "unauthorized" }, 401);
|
|
7343
|
-
}
|
|
7344
|
-
if (typeof authSvc?.getAuthContext !== "function") {
|
|
7345
|
-
return c.json({ error: "auth_service_unavailable" }, 503);
|
|
7346
|
-
}
|
|
7347
|
-
const handoffAuthCtx = await authSvc.getAuthContext();
|
|
7348
|
-
const internal = handoffAuthCtx?.internalAdapter;
|
|
7349
|
-
if (!internal?.createVerificationValue) {
|
|
7350
|
-
return c.json({ error: "verification_api_unavailable" }, 503);
|
|
7351
|
-
}
|
|
7352
|
-
let body = {};
|
|
7353
|
-
try {
|
|
7354
|
-
body = await c.req.json();
|
|
7355
|
-
} catch {
|
|
7356
|
-
body = {};
|
|
7357
|
-
}
|
|
7358
|
-
const email = String(body?.email ?? "").toLowerCase().trim();
|
|
7359
|
-
if (!email) return c.json({ error: "email_required" }, 400);
|
|
7360
|
-
const name = body?.name == null ? null : String(body.name);
|
|
7361
|
-
const by = body?.by == null ? "service" : String(body.by);
|
|
7362
|
-
const envIdInBody = body?.envId == null ? null : String(body.envId);
|
|
7363
|
-
const handoff = randomUUID2().replace(/-/g, "") + randomUUID2().replace(/-/g, "");
|
|
7364
|
-
const ttlSec = 60;
|
|
7365
|
-
const expiresAt = new Date(Date.now() + ttlSec * 1e3);
|
|
7366
|
-
await internal.createVerificationValue({
|
|
7367
|
-
identifier: `sso-handoff:${handoff}`,
|
|
7368
|
-
value: JSON.stringify({ email, name, by, envId: envIdInBody ?? environmentId }),
|
|
7369
|
-
expiresAt
|
|
7370
|
-
});
|
|
7371
|
-
return c.json({
|
|
7372
|
-
token: handoff,
|
|
7373
|
-
expiresAt: expiresAt.toISOString(),
|
|
7374
|
-
ttlSec
|
|
7375
|
-
});
|
|
7376
|
-
} catch (err) {
|
|
7377
|
-
ctx.logger?.error?.("[AuthProxyPlugin] sso-handoff-issue failed", err instanceof Error ? err : new Error(String(err)));
|
|
7378
|
-
return c.json({ error: "sso_handoff_issue_failed", message: String(err?.message ?? err) }, 500);
|
|
7379
|
-
}
|
|
7380
|
-
}
|
|
7381
|
-
if (c.req.method === "GET" && subPath === "sso-exchange") {
|
|
7382
|
-
try {
|
|
7383
|
-
const token = (url.searchParams.get("token") ?? "").trim();
|
|
7384
|
-
const nextRaw = url.searchParams.get("next") ?? "/";
|
|
7385
|
-
const next = nextRaw.startsWith("/") ? nextRaw : "/";
|
|
7386
|
-
if (!token) return c.text("missing token", 400);
|
|
7387
|
-
if (typeof authSvc?.getAuthContext !== "function") {
|
|
7388
|
-
return c.text("auth service unavailable", 503);
|
|
7389
|
-
}
|
|
7390
|
-
const authCtx = await authSvc.getAuthContext();
|
|
7391
|
-
const internal = authCtx?.internalAdapter;
|
|
7392
|
-
if (!internal?.consumeVerificationValue) {
|
|
7393
|
-
return c.text("verification API unavailable", 503);
|
|
7394
|
-
}
|
|
7395
|
-
const consumed = await internal.consumeVerificationValue(`sso-handoff:${token}`);
|
|
7396
|
-
if (!consumed) return c.text("invalid or expired token", 401);
|
|
7397
|
-
const expiresAt = consumed?.expiresAt ? new Date(consumed.expiresAt).getTime() : 0;
|
|
7398
|
-
if (!expiresAt || expiresAt < Date.now()) return c.text("expired token", 401);
|
|
7399
|
-
let payload = {};
|
|
7400
|
-
try {
|
|
7401
|
-
payload = JSON.parse(String(consumed.value));
|
|
7402
|
-
} catch {
|
|
7403
|
-
payload = { email: String(consumed.value) };
|
|
7404
|
-
}
|
|
7405
|
-
const email = String(payload.email ?? "").toLowerCase().trim();
|
|
7406
|
-
if (!email) return c.text("handoff missing email", 400);
|
|
7407
|
-
const found = await internal.findUserByEmail(email, { includeAccounts: true });
|
|
7408
|
-
let userId = found?.user?.id;
|
|
7409
|
-
let hasCredentialAccount = (found?.accounts ?? []).some((a) => a.providerId === "credential" && a.password);
|
|
7410
|
-
if (!userId) {
|
|
7411
|
-
const created = await internal.createUser({
|
|
7412
|
-
email,
|
|
7413
|
-
name: payload.name ?? email,
|
|
7414
|
-
emailVerified: true
|
|
7415
|
-
});
|
|
7416
|
-
userId = created?.id;
|
|
7417
|
-
hasCredentialAccount = false;
|
|
7418
|
-
}
|
|
7419
|
-
if (!userId) return c.text("failed to provision user", 500);
|
|
7420
|
-
const session = await internal.createSession(userId, false);
|
|
7421
|
-
const rawToken = session?.token;
|
|
7422
|
-
const sessionExpiresAt = session?.expiresAt ? new Date(session.expiresAt) : new Date(Date.now() + 7 * 24 * 3600 * 1e3);
|
|
7423
|
-
if (!rawToken) return c.text("failed to mint session", 500);
|
|
7424
|
-
const secret = authCtx?.secret ?? "";
|
|
7425
|
-
if (!secret) return c.text("auth secret unavailable", 503);
|
|
7426
|
-
const cookieName = authCtx?.authCookies?.sessionToken?.name ?? "better-auth.session_token";
|
|
7427
|
-
const cookieAttrs = authCtx?.authCookies?.sessionToken?.attributes ?? {};
|
|
7428
|
-
const encoded = signSessionCookieValue(rawToken, secret);
|
|
7429
|
-
const maxAgeSec = Math.max(60, Math.floor((sessionExpiresAt.getTime() - Date.now()) / 1e3));
|
|
7430
|
-
const setCookie = buildSetCookieHeader(cookieName, encoded, cookieAttrs, maxAgeSec);
|
|
7431
|
-
const finalNext = hasCredentialAccount ? next : `/_console/system/profile?recovery_needed=true&next=${encodeURIComponent(next)}`;
|
|
7432
|
-
const headers = new Headers();
|
|
7433
|
-
headers.set("Set-Cookie", setCookie);
|
|
7434
|
-
headers.set("Location", finalNext);
|
|
7435
|
-
headers.set("Cache-Control", "no-store");
|
|
7436
|
-
return new Response(null, { status: 302, headers });
|
|
7437
|
-
} catch (err) {
|
|
7438
|
-
ctx.logger?.error?.("[AuthProxyPlugin] sso-exchange failed", err instanceof Error ? err : new Error(String(err)));
|
|
7439
|
-
return c.text(`sso-exchange failed: ${err?.message ?? String(err)}`, 500);
|
|
7440
|
-
}
|
|
7441
|
-
}
|
|
7442
|
-
if (c.req.method === "POST" && subPath === "set-initial-password") {
|
|
7443
|
-
try {
|
|
7444
|
-
let body = {};
|
|
7445
|
-
try {
|
|
7446
|
-
body = await c.req.json();
|
|
7447
|
-
} catch {
|
|
7448
|
-
body = {};
|
|
7449
|
-
}
|
|
7450
|
-
const newPassword = body?.newPassword;
|
|
7451
|
-
if (typeof newPassword !== "string" || newPassword.length === 0) {
|
|
7452
|
-
return c.json({ success: false, error: { code: "invalid_request", message: "newPassword is required" } }, 400);
|
|
7453
|
-
}
|
|
7454
|
-
if (typeof authSvc?.getAuthContext !== "function") {
|
|
7455
|
-
return c.json({ success: false, error: { code: "unavailable", message: "Auth context unavailable" } }, 503);
|
|
7456
|
-
}
|
|
7457
|
-
let userId;
|
|
7458
|
-
try {
|
|
7459
|
-
const api = typeof authSvc.getApi === "function" ? await authSvc.getApi() : null;
|
|
7460
|
-
const session = await api?.getSession?.({ headers: c.req.raw.headers });
|
|
7461
|
-
userId = session?.user?.id ? String(session.user.id) : void 0;
|
|
7462
|
-
} catch {
|
|
7463
|
-
}
|
|
7464
|
-
if (!userId) {
|
|
7465
|
-
return c.json({ success: false, error: { code: "unauthorized", message: "Sign in first" } }, 401);
|
|
7466
|
-
}
|
|
7467
|
-
const setPwCtx = await authSvc.getAuthContext();
|
|
7468
|
-
if (!setPwCtx?.internalAdapter || !setPwCtx?.password) {
|
|
7469
|
-
return c.json({ success: false, error: { code: "unavailable", message: "Auth context unavailable" } }, 503);
|
|
7470
|
-
}
|
|
7471
|
-
const minLen = setPwCtx.password?.config?.minPasswordLength ?? 8;
|
|
7472
|
-
const maxLen = setPwCtx.password?.config?.maxPasswordLength ?? 128;
|
|
7473
|
-
if (newPassword.length < minLen) {
|
|
7474
|
-
return c.json({ success: false, error: { code: "password_too_short", message: `Password must be at least ${minLen} characters` } }, 400);
|
|
7475
|
-
}
|
|
7476
|
-
if (newPassword.length > maxLen) {
|
|
7477
|
-
return c.json({ success: false, error: { code: "password_too_long", message: `Password must be at most ${maxLen} characters` } }, 400);
|
|
7478
|
-
}
|
|
7479
|
-
const accounts = await setPwCtx.internalAdapter.findAccounts(userId);
|
|
7480
|
-
const existingCredential = accounts?.find?.((a) => a.providerId === "credential" && a.password);
|
|
7481
|
-
if (existingCredential) {
|
|
7482
|
-
return c.json({ success: false, error: { code: "credential_account_exists", message: "A local password is already set for this account. Use change-password instead." } }, 409);
|
|
7483
|
-
}
|
|
7484
|
-
const passwordHash = await setPwCtx.password.hash(newPassword);
|
|
7485
|
-
await setPwCtx.internalAdapter.createAccount({
|
|
7486
|
-
userId,
|
|
7487
|
-
providerId: "credential",
|
|
7488
|
-
accountId: userId,
|
|
7489
|
-
password: passwordHash
|
|
7490
|
-
});
|
|
7491
|
-
return c.json({ success: true });
|
|
7492
|
-
} catch (err) {
|
|
7493
|
-
ctx.logger?.error?.("[AuthProxyPlugin] set-initial-password failed", err instanceof Error ? err : new Error(String(err)));
|
|
7494
|
-
return c.json({ success: false, error: { code: "set_password_failed", message: String(err?.message ?? err) } }, 500);
|
|
7495
|
-
}
|
|
7496
|
-
}
|
|
7497
|
-
const fn = await resolveAuthHandler(authSvc);
|
|
7498
|
-
if (!fn) {
|
|
7499
|
-
return c.json({ error: "auth_service_unavailable", environmentId }, 503);
|
|
7500
|
-
}
|
|
7501
|
-
const resp = await fn(c.req.raw);
|
|
7502
|
-
const rootDomain = process.env.OS_ROOT_DOMAIN || "";
|
|
7503
|
-
if (rootDomain) {
|
|
7504
|
-
const leakyDomain = rootDomain.startsWith(".") ? rootDomain : `.${rootDomain}`;
|
|
7505
|
-
const leakyNames = [
|
|
7506
|
-
"__Secure-better-auth.session_token",
|
|
7507
|
-
"better-auth.session_token",
|
|
7508
|
-
"__Secure-better-auth.state",
|
|
7509
|
-
"better-auth.state",
|
|
7510
|
-
"__Secure-better-auth.csrf_token",
|
|
7511
|
-
"better-auth.csrf_token"
|
|
7512
|
-
];
|
|
7513
|
-
try {
|
|
7514
|
-
for (const n of leakyNames) {
|
|
7515
|
-
const isSecure = n.startsWith("__Secure-");
|
|
7516
|
-
const attrs = `Max-Age=0; Path=/; Domain=${leakyDomain}; SameSite=Lax${isSecure ? "; Secure" : ""}`;
|
|
7517
|
-
resp.headers?.append?.("Set-Cookie", `${n}=; ${attrs}`);
|
|
7518
|
-
}
|
|
7519
|
-
} catch {
|
|
7520
|
-
}
|
|
7521
|
-
}
|
|
7522
|
-
return resp;
|
|
7523
|
-
} catch (err) {
|
|
7524
|
-
ctx.logger?.error?.("[AuthProxyPlugin] auth dispatch failed", {
|
|
7525
|
-
error: err?.message,
|
|
7526
|
-
stack: err?.stack
|
|
7527
|
-
});
|
|
7528
|
-
return c.json({
|
|
7529
|
-
error: "auth_dispatch_failed",
|
|
7530
|
-
message: err?.message ?? String(err)
|
|
7531
|
-
}, 500);
|
|
7532
|
-
}
|
|
7533
|
-
};
|
|
7534
|
-
if (typeof rawApp.all === "function") {
|
|
7535
|
-
rawApp.all(`${AUTH_PREFIX}/*`, handler);
|
|
7536
|
-
} else {
|
|
7537
|
-
for (const m of ["get", "post", "put", "delete", "patch", "options"]) {
|
|
7538
|
-
try {
|
|
7539
|
-
rawApp[m]?.(`${AUTH_PREFIX}/*`, handler);
|
|
7540
|
-
} catch {
|
|
7541
|
-
}
|
|
7542
|
-
}
|
|
7543
|
-
}
|
|
7544
|
-
ctx.logger?.info?.(`[AuthProxyPlugin] auth proxy mounted at ${AUTH_PREFIX}/*`);
|
|
7545
|
-
});
|
|
7546
|
-
};
|
|
7547
|
-
}
|
|
7548
|
-
};
|
|
7549
|
-
|
|
7550
|
-
// src/cloud/cloud-url.ts
|
|
7551
|
-
var DEFAULT_CLOUD_URL = "https://cloud.objectos.ai";
|
|
7552
|
-
function resolveCloudUrl(explicit) {
|
|
7553
|
-
const raw = (explicit ?? process.env.OS_CLOUD_URL ?? "").trim();
|
|
7554
|
-
const lower = raw.toLowerCase();
|
|
7555
|
-
if (lower === "off" || lower === "none" || lower === "local" || lower === "disabled") {
|
|
7556
|
-
return "";
|
|
7557
|
-
}
|
|
7558
|
-
const picked = raw || DEFAULT_CLOUD_URL;
|
|
7559
|
-
return picked.replace(/\/+$/, "");
|
|
7560
|
-
}
|
|
7561
|
-
|
|
7562
|
-
// src/cloud/marketplace-public-url.ts
|
|
7563
|
-
function resolveMarketplacePublicBaseUrl(explicit) {
|
|
7564
|
-
const raw = (explicit ?? process.env.OS_MARKETPLACE_PUBLIC_BASE_URL ?? "").trim();
|
|
7565
|
-
const lower = raw.toLowerCase();
|
|
7566
|
-
if (!raw || lower === "off" || lower === "none" || lower === "disabled" || lower === "false") {
|
|
7567
|
-
return "";
|
|
7568
|
-
}
|
|
7569
|
-
return raw.replace(/\/+$/, "");
|
|
7570
|
-
}
|
|
7571
|
-
function publicMarketplaceKeyForApiPath(pathname) {
|
|
7572
|
-
const prefix = "/api/v1/marketplace/packages";
|
|
7573
|
-
if (pathname === prefix) return "packages.json";
|
|
7574
|
-
if (!pathname.startsWith(`${prefix}/`)) return null;
|
|
7575
|
-
const tail = pathname.slice(prefix.length + 1);
|
|
7576
|
-
if (!tail) return null;
|
|
7577
|
-
const parts = tail.split("/");
|
|
7578
|
-
if (parts.length === 1) {
|
|
7579
|
-
const id = decodeURIComponent(parts[0] ?? "");
|
|
7580
|
-
if (!id) return null;
|
|
7581
|
-
return `packages/${encodeURIComponent(id)}.json`;
|
|
7582
|
-
}
|
|
7583
|
-
if (parts.length === 4 && parts[1] === "versions" && parts[3] === "manifest") {
|
|
7584
|
-
const id = decodeURIComponent(parts[0] ?? "");
|
|
7585
|
-
const versionId = decodeURIComponent(parts[2] ?? "");
|
|
7586
|
-
if (!id || !versionId) return null;
|
|
7587
|
-
return `packages/${encodeURIComponent(id)}/versions/${encodeURIComponent(versionId)}/manifest.json`;
|
|
6245
|
+
if (parts.length === 4 && parts[1] === "versions" && parts[3] === "manifest") {
|
|
6246
|
+
const id = decodeURIComponent(parts[0] ?? "");
|
|
6247
|
+
const versionId = decodeURIComponent(parts[2] ?? "");
|
|
6248
|
+
if (!id || !versionId) return null;
|
|
6249
|
+
return `packages/${encodeURIComponent(id)}/versions/${encodeURIComponent(versionId)}/manifest.json`;
|
|
7588
6250
|
}
|
|
7589
6251
|
return null;
|
|
7590
6252
|
}
|
|
@@ -7679,13 +6341,7 @@ var MarketplaceProxyPlugin = class _MarketplaceProxyPlugin {
|
|
|
7679
6341
|
}
|
|
7680
6342
|
const target = `${cloudUrl}${incomingUrl.pathname}${incomingUrl.search}`;
|
|
7681
6343
|
if (method !== "GET" && method !== "HEAD") {
|
|
7682
|
-
return
|
|
7683
|
-
success: false,
|
|
7684
|
-
error: {
|
|
7685
|
-
code: "marketplace_method_not_allowed",
|
|
7686
|
-
message: `Marketplace proxy only forwards GET/HEAD; install via cloud.`
|
|
7687
|
-
}
|
|
7688
|
-
}, 405);
|
|
6344
|
+
return next();
|
|
7689
6345
|
}
|
|
7690
6346
|
const accept = c.req.header("accept") ?? "application/json";
|
|
7691
6347
|
const acceptLang = c.req.header("accept-language") ?? "";
|
|
@@ -7886,356 +6542,10 @@ async function consumeAndMaybeCache(resp, key, pathname, method, cache) {
|
|
|
7886
6542
|
return new Response(outBody, { status: resp.status, headers: respHeaders });
|
|
7887
6543
|
}
|
|
7888
6544
|
|
|
7889
|
-
// src/cloud/runtime-config-plugin.ts
|
|
7890
|
-
var RuntimeConfigPlugin = class {
|
|
7891
|
-
constructor(config = {}) {
|
|
7892
|
-
this.name = "com.objectstack.runtime.runtime-config";
|
|
7893
|
-
this.version = "1.0.0";
|
|
7894
|
-
this.init = async (_ctx) => {
|
|
7895
|
-
};
|
|
7896
|
-
this.start = async (ctx) => {
|
|
7897
|
-
ctx.hook("kernel:ready", async () => {
|
|
7898
|
-
let httpServer;
|
|
7899
|
-
try {
|
|
7900
|
-
httpServer = ctx.getService("http-server");
|
|
7901
|
-
} catch {
|
|
7902
|
-
ctx.logger?.warn?.("[RuntimeConfigPlugin] http-server not available \u2014 runtime/config not mounted");
|
|
7903
|
-
return;
|
|
7904
|
-
}
|
|
7905
|
-
if (!httpServer || typeof httpServer.getRawApp !== "function") {
|
|
7906
|
-
ctx.logger?.warn?.("[RuntimeConfigPlugin] http-server missing getRawApp() \u2014 runtime/config not mounted");
|
|
7907
|
-
return;
|
|
7908
|
-
}
|
|
7909
|
-
const rawApp = httpServer.getRawApp();
|
|
7910
|
-
const features = {
|
|
7911
|
-
installLocal: this.installLocal,
|
|
7912
|
-
marketplace: true
|
|
7913
|
-
};
|
|
7914
|
-
let envRegistry = null;
|
|
7915
|
-
try {
|
|
7916
|
-
envRegistry = ctx.getService("env-registry");
|
|
7917
|
-
} catch {
|
|
7918
|
-
}
|
|
7919
|
-
const handler = async (c) => {
|
|
7920
|
-
const rawHost = c.req.header("host") ?? "";
|
|
7921
|
-
const host = rawHost.split(":")[0].toLowerCase().trim();
|
|
7922
|
-
let defaultEnvironmentId;
|
|
7923
|
-
let defaultOrgId;
|
|
7924
|
-
let resolvedSingleEnv = this.singleEnvironment;
|
|
7925
|
-
const resolveFn = typeof envRegistry?.resolveByHostname === "function" ? envRegistry.resolveByHostname.bind(envRegistry) : typeof envRegistry?.resolveHostname === "function" ? envRegistry.resolveHostname.bind(envRegistry) : null;
|
|
7926
|
-
if (resolveFn && host) {
|
|
7927
|
-
try {
|
|
7928
|
-
const resolved = await resolveFn(host);
|
|
7929
|
-
if (resolved?.environmentId) {
|
|
7930
|
-
defaultEnvironmentId = String(resolved.environmentId);
|
|
7931
|
-
const orgId = resolved.organizationId ?? resolved.organization_id;
|
|
7932
|
-
if (orgId) defaultOrgId = String(orgId);
|
|
7933
|
-
resolvedSingleEnv = true;
|
|
7934
|
-
}
|
|
7935
|
-
} catch {
|
|
7936
|
-
}
|
|
7937
|
-
}
|
|
7938
|
-
return c.json({
|
|
7939
|
-
cloudUrl: this.cloudUrl,
|
|
7940
|
-
singleEnvironment: resolvedSingleEnv,
|
|
7941
|
-
defaultOrgId,
|
|
7942
|
-
defaultEnvironmentId,
|
|
7943
|
-
features,
|
|
7944
|
-
branding: {
|
|
7945
|
-
productName: this.productName,
|
|
7946
|
-
productShortName: this.productShortName
|
|
7947
|
-
}
|
|
7948
|
-
});
|
|
7949
|
-
};
|
|
7950
|
-
rawApp.get("/api/v1/runtime/config", handler);
|
|
7951
|
-
rawApp.get("/api/v1/studio/runtime-config", handler);
|
|
7952
|
-
ctx.logger?.info?.("[RuntimeConfigPlugin] mounted /api/v1/runtime/config", {
|
|
7953
|
-
cloudUrl: this.cloudUrl || "(empty)",
|
|
7954
|
-
installLocal: this.installLocal,
|
|
7955
|
-
perHostEnvResolution: !!envRegistry
|
|
7956
|
-
});
|
|
7957
|
-
});
|
|
7958
|
-
};
|
|
7959
|
-
this.destroy = async () => {
|
|
7960
|
-
};
|
|
7961
|
-
this.cloudUrl = config.controlPlaneUrl === "" ? "" : resolveCloudUrl(config.controlPlaneUrl) ?? "";
|
|
7962
|
-
this.installLocal = !!config.installLocal;
|
|
7963
|
-
this.singleEnvironment = !!config.singleEnvironment;
|
|
7964
|
-
const envName = (typeof process !== "undefined" ? process.env?.OS_PRODUCT_NAME : void 0)?.trim();
|
|
7965
|
-
const envShort = (typeof process !== "undefined" ? process.env?.OS_PRODUCT_SHORT_NAME : void 0)?.trim();
|
|
7966
|
-
this.productName = (config.productName ?? envName ?? "ObjectOS").trim() || "ObjectOS";
|
|
7967
|
-
this.productShortName = (config.productShortName ?? envShort ?? this.productName).trim() || this.productName;
|
|
7968
|
-
}
|
|
7969
|
-
};
|
|
7970
|
-
|
|
7971
|
-
// src/cloud/file-artifact-api-client.ts
|
|
7972
|
-
import { readFile as readFile2, stat } from "fs/promises";
|
|
7973
|
-
import { resolve as resolvePath4 } from "path";
|
|
7974
|
-
var FileArtifactApiClient = class {
|
|
7975
|
-
constructor(config = {}) {
|
|
7976
|
-
const cwd = process.cwd();
|
|
7977
|
-
this.artifactPath = resolvePath4(
|
|
7978
|
-
cwd,
|
|
7979
|
-
config.artifactPath ?? process.env.OS_ARTIFACT_PATH ?? "dist/objectstack.json"
|
|
7980
|
-
);
|
|
7981
|
-
this.environmentId = config.environmentId ?? process.env.OS_ENVIRONMENT_ID ?? "proj_local";
|
|
7982
|
-
this.organizationId = config.organizationId ?? process.env.OS_ORGANIZATION_ID ?? "org_local";
|
|
7983
|
-
this.overrideRuntime = config.runtime;
|
|
7984
|
-
this.watch = config.watch ?? true;
|
|
7985
|
-
this.logger = config.logger ?? console;
|
|
7986
|
-
}
|
|
7987
|
-
async resolveHostname(_host) {
|
|
7988
|
-
const runtime = this.overrideRuntime ?? await this.readRuntimeFromArtifact();
|
|
7989
|
-
return {
|
|
7990
|
-
environmentId: this.environmentId,
|
|
7991
|
-
organizationId: this.organizationId,
|
|
7992
|
-
...runtime ? { runtime } : {}
|
|
7993
|
-
};
|
|
7994
|
-
}
|
|
7995
|
-
async fetchArtifact(_environmentId, _opts) {
|
|
7996
|
-
return this.loadArtifact();
|
|
7997
|
-
}
|
|
7998
|
-
async lookupProjectByShortId(_shortId) {
|
|
7999
|
-
return { environmentId: this.environmentId, organizationId: this.organizationId };
|
|
8000
|
-
}
|
|
8001
|
-
async fetchBranchHead(_environmentId, _branchName) {
|
|
8002
|
-
const artifact = await this.loadArtifact();
|
|
8003
|
-
return artifact ? { commitId: artifact.commitId ?? "local", publishedAt: null } : null;
|
|
8004
|
-
}
|
|
8005
|
-
invalidate(_environmentId) {
|
|
8006
|
-
this.cached = void 0;
|
|
8007
|
-
}
|
|
8008
|
-
clear() {
|
|
8009
|
-
this.cached = void 0;
|
|
8010
|
-
}
|
|
8011
|
-
async loadArtifact() {
|
|
8012
|
-
try {
|
|
8013
|
-
const stats = await stat(this.artifactPath);
|
|
8014
|
-
const mtimeMs = stats.mtimeMs;
|
|
8015
|
-
if (!this.watch && this.cached) return this.cached.response;
|
|
8016
|
-
if (this.cached && this.cached.mtimeMs === mtimeMs) return this.cached.response;
|
|
8017
|
-
const raw = await readFile2(this.artifactPath, "utf8");
|
|
8018
|
-
const parsed = JSON.parse(raw);
|
|
8019
|
-
const isEnvelope = parsed && typeof parsed === "object" && typeof parsed.metadata === "object" && parsed.metadata !== null;
|
|
8020
|
-
const metadata = isEnvelope ? parsed.metadata : parsed;
|
|
8021
|
-
const runtime = this.overrideRuntime ?? (isEnvelope ? parsed.runtime : void 0) ?? this.deriveRuntimeFromMetadata(metadata) ?? this.defaultLocalSqliteRuntime();
|
|
8022
|
-
const response = {
|
|
8023
|
-
schemaVersion: parsed.schemaVersion ?? "1",
|
|
8024
|
-
environmentId: parsed.environmentId ?? this.environmentId,
|
|
8025
|
-
commitId: parsed.commitId ?? "local",
|
|
8026
|
-
checksum: parsed.checksum ?? "",
|
|
8027
|
-
publishedAt: parsed.publishedAt ?? (/* @__PURE__ */ new Date()).toISOString(),
|
|
8028
|
-
metadata,
|
|
8029
|
-
functions: parsed.functions,
|
|
8030
|
-
manifest: parsed.manifest,
|
|
8031
|
-
runtime: {
|
|
8032
|
-
organizationId: this.organizationId,
|
|
8033
|
-
...runtime
|
|
8034
|
-
}
|
|
8035
|
-
};
|
|
8036
|
-
this.cached = { mtimeMs, response };
|
|
8037
|
-
return response;
|
|
8038
|
-
} catch (err) {
|
|
8039
|
-
this.logger.error?.("[FileArtifactApiClient] failed to load artifact", {
|
|
8040
|
-
artifactPath: this.artifactPath,
|
|
8041
|
-
error: err?.message ?? err
|
|
8042
|
-
});
|
|
8043
|
-
return null;
|
|
8044
|
-
}
|
|
8045
|
-
}
|
|
8046
|
-
async readRuntimeFromArtifact() {
|
|
8047
|
-
const artifact = await this.loadArtifact();
|
|
8048
|
-
return artifact?.runtime;
|
|
8049
|
-
}
|
|
8050
|
-
deriveRuntimeFromMetadata(metadata) {
|
|
8051
|
-
const datasources = metadata?.datasources;
|
|
8052
|
-
if (!Array.isArray(datasources) || datasources.length === 0) return void 0;
|
|
8053
|
-
const mapping = metadata?.datasourceMapping;
|
|
8054
|
-
let preferredName;
|
|
8055
|
-
if (mapping) {
|
|
8056
|
-
const def = mapping.find((m) => m?.default === true);
|
|
8057
|
-
if (def?.datasource) preferredName = def.datasource;
|
|
8058
|
-
}
|
|
8059
|
-
const ds = preferredName ? datasources.find((d) => d?.name === preferredName) ?? datasources[0] : datasources[0];
|
|
8060
|
-
if (!ds || typeof ds !== "object") return void 0;
|
|
8061
|
-
const config = ds.config ?? {};
|
|
8062
|
-
const url = config.url ?? config.connectionString ?? config.connection ?? config.filename;
|
|
8063
|
-
const driver = ds.driver;
|
|
8064
|
-
if (typeof driver !== "string" || typeof url !== "string") return void 0;
|
|
8065
|
-
return {
|
|
8066
|
-
databaseDriver: driver,
|
|
8067
|
-
databaseUrl: url,
|
|
8068
|
-
databaseAuthToken: typeof config.authToken === "string" ? config.authToken : void 0
|
|
8069
|
-
};
|
|
8070
|
-
}
|
|
8071
|
-
defaultLocalSqliteRuntime() {
|
|
8072
|
-
const cwd = process.cwd();
|
|
8073
|
-
const dbPath = resolvePath4(cwd, ".objectstack/data", `${this.environmentId}.db`);
|
|
8074
|
-
return {
|
|
8075
|
-
databaseDriver: "sqlite",
|
|
8076
|
-
databaseUrl: `file:${dbPath}`
|
|
8077
|
-
};
|
|
8078
|
-
}
|
|
8079
|
-
};
|
|
8080
|
-
|
|
8081
|
-
// src/cloud/objectos-stack.ts
|
|
8082
|
-
async function createHostEnginePlugins() {
|
|
8083
|
-
const { ObjectQLPlugin } = await import("@objectstack/objectql");
|
|
8084
|
-
const { DriverPlugin: DriverPlugin2 } = await Promise.resolve().then(() => (init_driver_plugin(), driver_plugin_exports));
|
|
8085
|
-
const { MetadataPlugin } = await import("@objectstack/metadata");
|
|
8086
|
-
const { InMemoryDriver } = await import("@objectstack/driver-memory");
|
|
8087
|
-
const driver = new InMemoryDriver();
|
|
8088
|
-
const driverName = "memory";
|
|
8089
|
-
const oqlRef = { ql: null };
|
|
8090
|
-
const objectql = {
|
|
8091
|
-
name: "com.objectstack.engine.objectql",
|
|
8092
|
-
version: "0.0.0",
|
|
8093
|
-
async init(ctx) {
|
|
8094
|
-
const plugin = new ObjectQLPlugin();
|
|
8095
|
-
this._inner = plugin;
|
|
8096
|
-
if (plugin.init) await plugin.init(ctx);
|
|
8097
|
-
oqlRef.ql = plugin.ql ?? plugin;
|
|
8098
|
-
},
|
|
8099
|
-
async start(ctx) {
|
|
8100
|
-
const plugin = this._inner;
|
|
8101
|
-
if (plugin?.start) await plugin.start(ctx);
|
|
8102
|
-
},
|
|
8103
|
-
async destroy() {
|
|
8104
|
-
const plugin = this._inner;
|
|
8105
|
-
if (plugin?.destroy) await plugin.destroy();
|
|
8106
|
-
else if (plugin?.stop) await plugin.stop();
|
|
8107
|
-
}
|
|
8108
|
-
};
|
|
8109
|
-
const datasourceMapping = {
|
|
8110
|
-
name: "objectos-host-datasource-mapping",
|
|
8111
|
-
version: "0.0.0",
|
|
8112
|
-
dependencies: ["com.objectstack.engine.objectql"],
|
|
8113
|
-
async init() {
|
|
8114
|
-
const ql = oqlRef.ql;
|
|
8115
|
-
if (ql?.setDatasourceMapping) {
|
|
8116
|
-
ql.setDatasourceMapping([
|
|
8117
|
-
{ default: true, datasource: `com.objectstack.driver.${driverName}` }
|
|
8118
|
-
]);
|
|
8119
|
-
}
|
|
8120
|
-
}
|
|
8121
|
-
};
|
|
8122
|
-
const driverPlugin = new DriverPlugin2(driver, driverName);
|
|
8123
|
-
const metadata = new MetadataPlugin({
|
|
8124
|
-
watch: false,
|
|
8125
|
-
// The host kernel is a routing shell. It doesn't own metadata —
|
|
8126
|
-
// every per-project kernel registers its own.
|
|
8127
|
-
registerSystemObjects: false
|
|
8128
|
-
});
|
|
8129
|
-
return [objectql, datasourceMapping, driverPlugin, metadata];
|
|
8130
|
-
}
|
|
8131
|
-
var ObjectOSEnvironmentPlugin = class {
|
|
8132
|
-
constructor(config) {
|
|
8133
|
-
this.name = "com.objectstack.runtime.objectos-environment";
|
|
8134
|
-
this.version = "1.0.0";
|
|
8135
|
-
this.init = async (ctx) => {
|
|
8136
|
-
const client = this.config.client ?? (this.config.controlPlaneUrl === "file" ? new FileArtifactApiClient({
|
|
8137
|
-
...this.config.fileConfig ?? {},
|
|
8138
|
-
logger: ctx.logger
|
|
8139
|
-
}) : new ArtifactApiClient({
|
|
8140
|
-
controlPlaneUrl: this.config.controlPlaneUrl,
|
|
8141
|
-
apiKey: this.config.controlPlaneApiKey,
|
|
8142
|
-
cacheTtlMs: this.config.artifactCacheTtlMs,
|
|
8143
|
-
logger: ctx.logger
|
|
8144
|
-
}));
|
|
8145
|
-
this.client = client;
|
|
8146
|
-
const envRegistry = new ArtifactEnvironmentRegistry({
|
|
8147
|
-
client,
|
|
8148
|
-
cacheTtlMs: this.config.envCacheTtlMs,
|
|
8149
|
-
logger: ctx.logger
|
|
8150
|
-
});
|
|
8151
|
-
const factory = new ArtifactKernelFactory({
|
|
8152
|
-
client,
|
|
8153
|
-
envRegistry,
|
|
8154
|
-
logger: ctx.logger
|
|
8155
|
-
});
|
|
8156
|
-
const kernelManager = new KernelManager({
|
|
8157
|
-
factory,
|
|
8158
|
-
maxSize: this.config.kernelCacheSize,
|
|
8159
|
-
ttlMs: this.config.kernelTtlMs,
|
|
8160
|
-
logger: ctx.logger,
|
|
8161
|
-
// Only the HTTP client exposes /freshness; file-mode (CLI dev)
|
|
8162
|
-
// has no upstream to probe.
|
|
8163
|
-
freshnessProbe: this.config.controlPlaneUrl === "file" ? void 0 : async (envId, builtAtMs) => {
|
|
8164
|
-
const fresh = await client.getFreshness(envId);
|
|
8165
|
-
if (!fresh) return false;
|
|
8166
|
-
const t = fresh.lastPublishedAt ? Date.parse(fresh.lastPublishedAt) : NaN;
|
|
8167
|
-
if (!Number.isFinite(t)) return false;
|
|
8168
|
-
if (t <= builtAtMs) return false;
|
|
8169
|
-
try {
|
|
8170
|
-
client.invalidate(envId);
|
|
8171
|
-
} catch {
|
|
8172
|
-
}
|
|
8173
|
-
return true;
|
|
8174
|
-
}
|
|
8175
|
-
});
|
|
8176
|
-
this.kernelManager = kernelManager;
|
|
8177
|
-
ctx.registerService("env-registry", envRegistry);
|
|
8178
|
-
ctx.registerService("kernel-manager", kernelManager);
|
|
8179
|
-
ctx.registerService("artifact-api-client", client);
|
|
8180
|
-
ctx.logger.info?.("ObjectOSEnvironmentPlugin: registered env-registry + kernel-manager", {
|
|
8181
|
-
mode: this.config.controlPlaneUrl === "file" ? "file" : "http",
|
|
8182
|
-
controlPlaneUrl: this.config.controlPlaneUrl
|
|
8183
|
-
});
|
|
8184
|
-
};
|
|
8185
|
-
this.destroy = async () => {
|
|
8186
|
-
try {
|
|
8187
|
-
await this.kernelManager?.evictAll();
|
|
8188
|
-
} catch {
|
|
8189
|
-
}
|
|
8190
|
-
try {
|
|
8191
|
-
this.client?.clear();
|
|
8192
|
-
} catch {
|
|
8193
|
-
}
|
|
8194
|
-
};
|
|
8195
|
-
this.config = config;
|
|
8196
|
-
}
|
|
8197
|
-
};
|
|
8198
|
-
async function createObjectOSStack(config) {
|
|
8199
|
-
if (!config.controlPlaneUrl && !config.client) {
|
|
8200
|
-
throw new Error("[createObjectOSStack] either controlPlaneUrl or client is required");
|
|
8201
|
-
}
|
|
8202
|
-
const merged = {
|
|
8203
|
-
...config,
|
|
8204
|
-
kernelCacheSize: Number(process.env.OS_KERNEL_CACHE_SIZE ?? config.kernelCacheSize ?? 32),
|
|
8205
|
-
kernelTtlMs: Number(process.env.OS_KERNEL_TTL_MS ?? config.kernelTtlMs ?? 15 * 60 * 1e3),
|
|
8206
|
-
envCacheTtlMs: Number(process.env.OS_ENV_CACHE_TTL_MS ?? config.envCacheTtlMs ?? 5 * 60 * 1e3),
|
|
8207
|
-
artifactCacheTtlMs: Number(process.env.OS_ARTIFACT_CACHE_TTL_MS ?? config.artifactCacheTtlMs ?? 5 * 60 * 1e3)
|
|
8208
|
-
};
|
|
8209
|
-
const enginePlugins = await createHostEnginePlugins();
|
|
8210
|
-
return {
|
|
8211
|
-
plugins: [
|
|
8212
|
-
...enginePlugins,
|
|
8213
|
-
new ObjectOSEnvironmentPlugin(merged),
|
|
8214
|
-
new AuthProxyPlugin(),
|
|
8215
|
-
new MarketplaceProxyPlugin({ controlPlaneUrl: merged.controlPlaneUrl === "file" ? void 0 : merged.controlPlaneUrl }),
|
|
8216
|
-
new RuntimeConfigPlugin({ controlPlaneUrl: merged.controlPlaneUrl === "file" ? void 0 : merged.controlPlaneUrl, installLocal: false }),
|
|
8217
|
-
// Host-supplied product/policy plugins (the official seam — see
|
|
8218
|
-
// ObjectOSStackConfig.extraPlugins). Appended last so they mount
|
|
8219
|
-
// after the framework defaults.
|
|
8220
|
-
...config.extraPlugins ?? []
|
|
8221
|
-
],
|
|
8222
|
-
api: {
|
|
8223
|
-
enableProjectScoping: true,
|
|
8224
|
-
projectResolution: "auto",
|
|
8225
|
-
// ObjectOS is multi-tenant: anonymous /api/v1/data/* must never
|
|
8226
|
-
// leak per-project data across organisations. AuthProxyPlugin
|
|
8227
|
-
// verifies upstream tokens and populates ctx.userId; requireAuth
|
|
8228
|
-
// turns missing userId into 401 at the REST layer before the
|
|
8229
|
-
// request reaches the per-project kernel.
|
|
8230
|
-
requireAuth: true
|
|
8231
|
-
}
|
|
8232
|
-
};
|
|
8233
|
-
}
|
|
8234
|
-
|
|
8235
6545
|
// src/cloud/marketplace-install-local-plugin.ts
|
|
8236
6546
|
import { existsSync as existsSync3, mkdirSync as mkdirSync4, readFileSync as readFileSync2, readdirSync, unlinkSync, writeFileSync as writeFileSync3 } from "fs";
|
|
8237
6547
|
import { join as join2, resolve } from "path";
|
|
8238
|
-
import { readEnvWithDeprecation as
|
|
6548
|
+
import { readEnvWithDeprecation as readEnvWithDeprecation3 } from "@objectstack/types";
|
|
8239
6549
|
var ROUTE_BASE = "/api/v1/marketplace/install-local";
|
|
8240
6550
|
var DEFAULT_DIR = ".objectstack/installed-packages";
|
|
8241
6551
|
function safeFilename(manifestId) {
|
|
@@ -8779,7 +7089,7 @@ var MarketplaceInstallLocalPlugin = class {
|
|
|
8779
7089
|
}
|
|
8780
7090
|
}
|
|
8781
7091
|
if (opts.seedNow && datasets.length > 0) {
|
|
8782
|
-
const multiTenant = String(
|
|
7092
|
+
const multiTenant = String(readEnvWithDeprecation3("OS_MULTI_ORG_ENABLED", "OS_MULTI_TENANT") ?? "false").toLowerCase() !== "false";
|
|
8783
7093
|
try {
|
|
8784
7094
|
const ql = ctx.getService("objectql");
|
|
8785
7095
|
let metadata;
|
|
@@ -8897,6 +7207,90 @@ var MarketplaceInstallLocalPlugin = class {
|
|
|
8897
7207
|
}
|
|
8898
7208
|
};
|
|
8899
7209
|
|
|
7210
|
+
// src/cloud/runtime-config-plugin.ts
|
|
7211
|
+
var RuntimeConfigPlugin = class {
|
|
7212
|
+
constructor(config = {}) {
|
|
7213
|
+
this.name = "com.objectstack.runtime.runtime-config";
|
|
7214
|
+
this.version = "1.0.0";
|
|
7215
|
+
this.init = async (_ctx) => {
|
|
7216
|
+
};
|
|
7217
|
+
this.start = async (ctx) => {
|
|
7218
|
+
ctx.hook("kernel:ready", async () => {
|
|
7219
|
+
let httpServer;
|
|
7220
|
+
try {
|
|
7221
|
+
httpServer = ctx.getService("http-server");
|
|
7222
|
+
} catch {
|
|
7223
|
+
ctx.logger?.warn?.("[RuntimeConfigPlugin] http-server not available \u2014 runtime/config not mounted");
|
|
7224
|
+
return;
|
|
7225
|
+
}
|
|
7226
|
+
if (!httpServer || typeof httpServer.getRawApp !== "function") {
|
|
7227
|
+
ctx.logger?.warn?.("[RuntimeConfigPlugin] http-server missing getRawApp() \u2014 runtime/config not mounted");
|
|
7228
|
+
return;
|
|
7229
|
+
}
|
|
7230
|
+
const rawApp = httpServer.getRawApp();
|
|
7231
|
+
const features = {
|
|
7232
|
+
installLocal: this.installLocal,
|
|
7233
|
+
marketplace: true,
|
|
7234
|
+
aiStudio: this.aiStudio
|
|
7235
|
+
};
|
|
7236
|
+
let envRegistry = null;
|
|
7237
|
+
try {
|
|
7238
|
+
envRegistry = ctx.getService("env-registry");
|
|
7239
|
+
} catch {
|
|
7240
|
+
}
|
|
7241
|
+
const handler = async (c) => {
|
|
7242
|
+
const rawHost = c.req.header("host") ?? "";
|
|
7243
|
+
const host = rawHost.split(":")[0].toLowerCase().trim();
|
|
7244
|
+
let defaultEnvironmentId;
|
|
7245
|
+
let defaultOrgId;
|
|
7246
|
+
let resolvedSingleEnv = this.singleEnvironment;
|
|
7247
|
+
const resolveFn = typeof envRegistry?.resolveByHostname === "function" ? envRegistry.resolveByHostname.bind(envRegistry) : typeof envRegistry?.resolveHostname === "function" ? envRegistry.resolveHostname.bind(envRegistry) : null;
|
|
7248
|
+
if (resolveFn && host) {
|
|
7249
|
+
try {
|
|
7250
|
+
const resolved = await resolveFn(host);
|
|
7251
|
+
if (resolved?.environmentId) {
|
|
7252
|
+
defaultEnvironmentId = String(resolved.environmentId);
|
|
7253
|
+
const orgId = resolved.organizationId ?? resolved.organization_id;
|
|
7254
|
+
if (orgId) defaultOrgId = String(orgId);
|
|
7255
|
+
resolvedSingleEnv = true;
|
|
7256
|
+
}
|
|
7257
|
+
} catch {
|
|
7258
|
+
}
|
|
7259
|
+
}
|
|
7260
|
+
return c.json({
|
|
7261
|
+
cloudUrl: this.cloudUrl,
|
|
7262
|
+
singleEnvironment: resolvedSingleEnv,
|
|
7263
|
+
defaultOrgId,
|
|
7264
|
+
defaultEnvironmentId,
|
|
7265
|
+
features,
|
|
7266
|
+
branding: {
|
|
7267
|
+
productName: this.productName,
|
|
7268
|
+
productShortName: this.productShortName
|
|
7269
|
+
}
|
|
7270
|
+
});
|
|
7271
|
+
};
|
|
7272
|
+
rawApp.get("/api/v1/runtime/config", handler);
|
|
7273
|
+
rawApp.get("/api/v1/studio/runtime-config", handler);
|
|
7274
|
+
ctx.logger?.info?.("[RuntimeConfigPlugin] mounted /api/v1/runtime/config", {
|
|
7275
|
+
cloudUrl: this.cloudUrl || "(empty)",
|
|
7276
|
+
installLocal: this.installLocal,
|
|
7277
|
+
perHostEnvResolution: !!envRegistry
|
|
7278
|
+
});
|
|
7279
|
+
});
|
|
7280
|
+
};
|
|
7281
|
+
this.destroy = async () => {
|
|
7282
|
+
};
|
|
7283
|
+
this.cloudUrl = config.controlPlaneUrl === "" ? "" : resolveCloudUrl(config.controlPlaneUrl) ?? "";
|
|
7284
|
+
this.installLocal = !!config.installLocal;
|
|
7285
|
+
this.aiStudio = config.aiStudio !== false;
|
|
7286
|
+
this.singleEnvironment = !!config.singleEnvironment;
|
|
7287
|
+
const envName = (typeof process !== "undefined" ? process.env?.OS_PRODUCT_NAME : void 0)?.trim();
|
|
7288
|
+
const envShort = (typeof process !== "undefined" ? process.env?.OS_PRODUCT_SHORT_NAME : void 0)?.trim();
|
|
7289
|
+
this.productName = (config.productName ?? envName ?? "ObjectOS").trim() || "ObjectOS";
|
|
7290
|
+
this.productShortName = (config.productShortName ?? envShort ?? this.productName).trim() || this.productName;
|
|
7291
|
+
}
|
|
7292
|
+
};
|
|
7293
|
+
|
|
8900
7294
|
// src/sandbox/script-runner.ts
|
|
8901
7295
|
var UnimplementedScriptRunner = class {
|
|
8902
7296
|
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
@@ -8927,23 +7321,17 @@ import {
|
|
|
8927
7321
|
createRestApiPlugin
|
|
8928
7322
|
} from "@objectstack/rest";
|
|
8929
7323
|
export * from "@objectstack/core";
|
|
8930
|
-
import { readEnvWithDeprecation as
|
|
7324
|
+
import { readEnvWithDeprecation as readEnvWithDeprecation4, _resetEnvDeprecationWarnings } from "@objectstack/types";
|
|
8931
7325
|
export {
|
|
8932
7326
|
AppPlugin,
|
|
8933
|
-
ArtifactApiClient,
|
|
8934
|
-
ArtifactEnvironmentRegistry,
|
|
8935
|
-
ArtifactKernelFactory,
|
|
8936
|
-
AuthProxyPlugin,
|
|
8937
7327
|
DEFAULT_CLOUD_URL,
|
|
8938
7328
|
DEFAULT_RATE_LIMITS,
|
|
8939
7329
|
DriverPlugin,
|
|
8940
7330
|
ExternalValidationPlugin,
|
|
8941
|
-
FileArtifactApiClient,
|
|
8942
7331
|
HttpDispatcher,
|
|
8943
7332
|
HttpServer,
|
|
8944
7333
|
InMemoryErrorReporter,
|
|
8945
7334
|
InMemoryMetricsRegistry,
|
|
8946
|
-
KernelManager,
|
|
8947
7335
|
MarketplaceInstallLocalPlugin,
|
|
8948
7336
|
MarketplaceProxyPlugin,
|
|
8949
7337
|
MiddlewareManager,
|
|
@@ -8951,9 +7339,8 @@ export {
|
|
|
8951
7339
|
NoopMetricsRegistry,
|
|
8952
7340
|
OBSERVABILITY_ERRORS_SERVICE,
|
|
8953
7341
|
OBSERVABILITY_METRICS_SERVICE,
|
|
8954
|
-
|
|
7342
|
+
ObjectKernel3 as ObjectKernel,
|
|
8955
7343
|
ObservabilityServicePlugin,
|
|
8956
|
-
PLATFORM_SSO_PROVIDER_ID,
|
|
8957
7344
|
QuickJSScriptRunner,
|
|
8958
7345
|
RUNTIME_METRICS,
|
|
8959
7346
|
RateLimiter,
|
|
@@ -8968,8 +7355,6 @@ export {
|
|
|
8968
7355
|
UnimplementedScriptRunner,
|
|
8969
7356
|
_resetEnvDeprecationWarnings,
|
|
8970
7357
|
actionBodyRunnerFactory,
|
|
8971
|
-
backfillPlatformSsoClients,
|
|
8972
|
-
buildPlatformSsoRedirectUri,
|
|
8973
7358
|
buildSecurityHeaders,
|
|
8974
7359
|
collectBundleActions,
|
|
8975
7360
|
collectBundleFunctions,
|
|
@@ -8977,12 +7362,9 @@ export {
|
|
|
8977
7362
|
createDefaultHostConfig,
|
|
8978
7363
|
createDispatcherPlugin,
|
|
8979
7364
|
createExternalValidationPlugin,
|
|
8980
|
-
createObjectOSStack,
|
|
8981
7365
|
createRestApiPlugin,
|
|
8982
7366
|
createStandaloneStack,
|
|
8983
7367
|
createSystemEnvironmentPlugin,
|
|
8984
|
-
derivePlatformSsoClientId,
|
|
8985
|
-
derivePlatformSsoClientSecret,
|
|
8986
7368
|
extractRequestId,
|
|
8987
7369
|
formatTraceparent,
|
|
8988
7370
|
generateRequestId,
|
|
@@ -8992,13 +7374,12 @@ export {
|
|
|
8992
7374
|
mergeRuntimeModule,
|
|
8993
7375
|
parseTraceparent,
|
|
8994
7376
|
readArtifactSource,
|
|
8995
|
-
|
|
7377
|
+
readEnvWithDeprecation4 as readEnvWithDeprecation,
|
|
8996
7378
|
resolveCloudUrl,
|
|
8997
7379
|
resolveDefaultArtifactPath,
|
|
8998
7380
|
resolveErrorReporter,
|
|
8999
7381
|
resolveMetrics,
|
|
9000
7382
|
resolveObjectStackHome,
|
|
9001
|
-
resolveRequestId
|
|
9002
|
-
seedPlatformSsoClient
|
|
7383
|
+
resolveRequestId
|
|
9003
7384
|
};
|
|
9004
7385
|
//# sourceMappingURL=index.js.map
|