@objectstack/cloud-connection 9.3.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/LICENSE +202 -0
- package/README.md +52 -0
- package/dist/index.cjs +1833 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +1694 -0
- package/dist/index.d.ts +1694 -0
- package/dist/index.js +1780 -0
- package/dist/index.js.map +1 -0
- package/package.json +57 -0
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,1833 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
28
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
+
|
|
30
|
+
// src/index.ts
|
|
31
|
+
var index_exports = {};
|
|
32
|
+
__export(index_exports, {
|
|
33
|
+
CLOUD_CONNECTION_UI_BUNDLE: () => CLOUD_CONNECTION_UI_BUNDLE,
|
|
34
|
+
CloudConnectionPlugin: () => CloudConnectionPlugin,
|
|
35
|
+
CloudConnectionSettingsPage: () => CloudConnectionSettingsPage,
|
|
36
|
+
ConnectionCredentialStore: () => ConnectionCredentialStore,
|
|
37
|
+
DEFAULT_CLOUD_URL: () => DEFAULT_CLOUD_URL,
|
|
38
|
+
DEFAULT_CONNECTION_CREDENTIAL_PATH: () => DEFAULT_CONNECTION_CREDENTIAL_PATH,
|
|
39
|
+
DEFAULT_INSTALLED_PACKAGES_DIR: () => DEFAULT_INSTALLED_PACKAGES_DIR,
|
|
40
|
+
LocalManifestSource: () => LocalManifestSource,
|
|
41
|
+
MARKETPLACE_BROWSE_UI_BUNDLE: () => MARKETPLACE_BROWSE_UI_BUNDLE,
|
|
42
|
+
MARKETPLACE_INSTALLED_UI_BUNDLE: () => MARKETPLACE_INSTALLED_UI_BUNDLE,
|
|
43
|
+
MarketplaceInstallLocalPlugin: () => MarketplaceInstallLocalPlugin,
|
|
44
|
+
MarketplaceProxyPlugin: () => MarketplaceProxyPlugin,
|
|
45
|
+
RuntimeConfigPlugin: () => RuntimeConfigPlugin,
|
|
46
|
+
createCloudConnectionPlugin: () => createCloudConnectionPlugin,
|
|
47
|
+
publicMarketplaceKeyForApiPath: () => publicMarketplaceKeyForApiPath,
|
|
48
|
+
resolveCloudUrl: () => resolveCloudUrl,
|
|
49
|
+
resolveMarketplacePublicBaseUrl: () => resolveMarketplacePublicBaseUrl
|
|
50
|
+
});
|
|
51
|
+
module.exports = __toCommonJS(index_exports);
|
|
52
|
+
|
|
53
|
+
// src/cloud-url.ts
|
|
54
|
+
var DEFAULT_CLOUD_URL = "https://cloud.objectos.ai";
|
|
55
|
+
function resolveCloudUrl(explicit) {
|
|
56
|
+
const raw = (explicit ?? process.env.OS_CLOUD_URL ?? "").trim();
|
|
57
|
+
const lower = raw.toLowerCase();
|
|
58
|
+
if (lower === "off" || lower === "none" || lower === "local" || lower === "disabled") {
|
|
59
|
+
return "";
|
|
60
|
+
}
|
|
61
|
+
const picked = raw || DEFAULT_CLOUD_URL;
|
|
62
|
+
return picked.replace(/\/+$/, "");
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// src/marketplace-public-url.ts
|
|
66
|
+
function resolveMarketplacePublicBaseUrl(explicit) {
|
|
67
|
+
const raw = (explicit ?? process.env.OS_MARKETPLACE_PUBLIC_BASE_URL ?? "").trim();
|
|
68
|
+
const lower = raw.toLowerCase();
|
|
69
|
+
if (!raw || lower === "off" || lower === "none" || lower === "disabled" || lower === "false") {
|
|
70
|
+
return "";
|
|
71
|
+
}
|
|
72
|
+
return raw.replace(/\/+$/, "");
|
|
73
|
+
}
|
|
74
|
+
function publicMarketplaceKeyForApiPath(pathname) {
|
|
75
|
+
const prefix = "/api/v1/marketplace/packages";
|
|
76
|
+
if (pathname === prefix) return "packages.json";
|
|
77
|
+
if (!pathname.startsWith(`${prefix}/`)) return null;
|
|
78
|
+
const tail = pathname.slice(prefix.length + 1);
|
|
79
|
+
if (!tail) return null;
|
|
80
|
+
const parts = tail.split("/");
|
|
81
|
+
if (parts.length === 1) {
|
|
82
|
+
const id = decodeURIComponent(parts[0] ?? "");
|
|
83
|
+
if (!id) return null;
|
|
84
|
+
return `packages/${encodeURIComponent(id)}.json`;
|
|
85
|
+
}
|
|
86
|
+
if (parts.length === 4 && parts[1] === "versions" && parts[3] === "manifest") {
|
|
87
|
+
const id = decodeURIComponent(parts[0] ?? "");
|
|
88
|
+
const versionId = decodeURIComponent(parts[2] ?? "");
|
|
89
|
+
if (!id || !versionId) return null;
|
|
90
|
+
return `packages/${encodeURIComponent(id)}/versions/${encodeURIComponent(versionId)}/manifest.json`;
|
|
91
|
+
}
|
|
92
|
+
return null;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// src/marketplace-ui.ts
|
|
96
|
+
var MARKETPLACE_BROWSE_UI_BUNDLE = {
|
|
97
|
+
id: "com.objectstack.cloud-connection.marketplace-browse-ui",
|
|
98
|
+
namespace: "sys",
|
|
99
|
+
version: "0.1.0",
|
|
100
|
+
type: "plugin",
|
|
101
|
+
scope: "system",
|
|
102
|
+
name: "Marketplace Browse UI",
|
|
103
|
+
description: "Setup navigation for the public marketplace catalog (browse).",
|
|
104
|
+
navigationContributions: [
|
|
105
|
+
{
|
|
106
|
+
app: "setup",
|
|
107
|
+
group: "group_apps",
|
|
108
|
+
priority: 100,
|
|
109
|
+
items: [
|
|
110
|
+
{ id: "nav_marketplace_browse", type: "url", label: "Browse Marketplace", url: "/apps/setup/system/marketplace", icon: "store" }
|
|
111
|
+
]
|
|
112
|
+
}
|
|
113
|
+
]
|
|
114
|
+
};
|
|
115
|
+
var MarketplaceInstalledPage = {
|
|
116
|
+
name: "marketplace_installed",
|
|
117
|
+
label: "Installed Apps",
|
|
118
|
+
type: "app",
|
|
119
|
+
template: "default",
|
|
120
|
+
kind: "full",
|
|
121
|
+
isDefault: false,
|
|
122
|
+
regions: [
|
|
123
|
+
{
|
|
124
|
+
name: "header",
|
|
125
|
+
width: "full",
|
|
126
|
+
components: [
|
|
127
|
+
{
|
|
128
|
+
type: "page:header",
|
|
129
|
+
properties: {
|
|
130
|
+
title: "Installed Apps",
|
|
131
|
+
subtitle: "Marketplace packages currently installed into this runtime's kernel.",
|
|
132
|
+
icon: "package-check"
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
]
|
|
136
|
+
},
|
|
137
|
+
{
|
|
138
|
+
name: "main",
|
|
139
|
+
width: "large",
|
|
140
|
+
components: [
|
|
141
|
+
{ type: "marketplace:installed-list", properties: {} }
|
|
142
|
+
]
|
|
143
|
+
}
|
|
144
|
+
]
|
|
145
|
+
};
|
|
146
|
+
var MARKETPLACE_INSTALLED_UI_BUNDLE = {
|
|
147
|
+
id: "com.objectstack.cloud-connection.marketplace-installed-ui",
|
|
148
|
+
namespace: "sys",
|
|
149
|
+
version: "0.2.0",
|
|
150
|
+
type: "plugin",
|
|
151
|
+
scope: "system",
|
|
152
|
+
name: "Marketplace Installed UI",
|
|
153
|
+
description: "Installed Apps page + Setup navigation for locally-installed marketplace packages.",
|
|
154
|
+
pages: [MarketplaceInstalledPage],
|
|
155
|
+
navigationContributions: [
|
|
156
|
+
{
|
|
157
|
+
app: "setup",
|
|
158
|
+
group: "group_apps",
|
|
159
|
+
priority: 110,
|
|
160
|
+
items: [
|
|
161
|
+
{ id: "nav_marketplace_installed", type: "page", pageName: "marketplace_installed", label: "Installed Apps", icon: "package-check" }
|
|
162
|
+
]
|
|
163
|
+
}
|
|
164
|
+
]
|
|
165
|
+
};
|
|
166
|
+
|
|
167
|
+
// src/marketplace-proxy-plugin.ts
|
|
168
|
+
var MARKETPLACE_PREFIX = "/api/v1/marketplace";
|
|
169
|
+
var DEFAULT_LRU_MAX = 200;
|
|
170
|
+
var LIST_TTL_MS = 30 * 60 * 1e3;
|
|
171
|
+
var PACKAGE_TTL_MS = 2 * 60 * 60 * 1e3;
|
|
172
|
+
var VERSION_TTL_MS = 24 * 60 * 60 * 1e3;
|
|
173
|
+
function ttlForPath(pathname) {
|
|
174
|
+
if (/\/packages\/[^/]+\/versions\//.test(pathname)) return VERSION_TTL_MS;
|
|
175
|
+
if (/\/packages\/[^/]+/.test(pathname)) return PACKAGE_TTL_MS;
|
|
176
|
+
return LIST_TTL_MS;
|
|
177
|
+
}
|
|
178
|
+
var LruTtlCache = class {
|
|
179
|
+
constructor(max) {
|
|
180
|
+
this.max = max;
|
|
181
|
+
this.map = /* @__PURE__ */ new Map();
|
|
182
|
+
}
|
|
183
|
+
get(key) {
|
|
184
|
+
const entry = this.map.get(key);
|
|
185
|
+
if (!entry) return void 0;
|
|
186
|
+
this.map.delete(key);
|
|
187
|
+
this.map.set(key, entry);
|
|
188
|
+
return entry;
|
|
189
|
+
}
|
|
190
|
+
set(key, entry) {
|
|
191
|
+
if (this.map.has(key)) this.map.delete(key);
|
|
192
|
+
this.map.set(key, entry);
|
|
193
|
+
while (this.map.size > this.max) {
|
|
194
|
+
const oldest = this.map.keys().next().value;
|
|
195
|
+
if (oldest === void 0) break;
|
|
196
|
+
this.map.delete(oldest);
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
clear() {
|
|
200
|
+
this.map.clear();
|
|
201
|
+
}
|
|
202
|
+
};
|
|
203
|
+
var MarketplaceProxyPlugin = class _MarketplaceProxyPlugin {
|
|
204
|
+
constructor(config = {}) {
|
|
205
|
+
this.name = "com.objectstack.runtime.marketplace-proxy";
|
|
206
|
+
this.version = "1.1.0";
|
|
207
|
+
this.init = async (_ctx) => {
|
|
208
|
+
};
|
|
209
|
+
this.start = async (ctx) => {
|
|
210
|
+
ctx.hook("kernel:ready", async () => {
|
|
211
|
+
try {
|
|
212
|
+
const manifest = ctx.getService("manifest");
|
|
213
|
+
manifest?.register?.(MARKETPLACE_BROWSE_UI_BUNDLE);
|
|
214
|
+
} catch {
|
|
215
|
+
}
|
|
216
|
+
let httpServer;
|
|
217
|
+
try {
|
|
218
|
+
httpServer = ctx.getService("http-server");
|
|
219
|
+
} catch {
|
|
220
|
+
ctx.logger?.warn?.("[MarketplaceProxyPlugin] http-server not available \u2014 marketplace routes not mounted");
|
|
221
|
+
return;
|
|
222
|
+
}
|
|
223
|
+
if (!httpServer || typeof httpServer.getRawApp !== "function") {
|
|
224
|
+
ctx.logger?.warn?.("[MarketplaceProxyPlugin] http-server missing getRawApp() \u2014 marketplace routes not mounted");
|
|
225
|
+
return;
|
|
226
|
+
}
|
|
227
|
+
const rawApp = httpServer.getRawApp();
|
|
228
|
+
const cloudUrl = this.cloudUrl;
|
|
229
|
+
const publicBaseUrl = this.publicBaseUrl;
|
|
230
|
+
const cache = this.cache;
|
|
231
|
+
if (publicBaseUrl) {
|
|
232
|
+
ctx.logger?.info?.(`[MarketplaceProxyPlugin] public R2 fast-path enabled \u2192 ${publicBaseUrl}`);
|
|
233
|
+
}
|
|
234
|
+
const handler = async (c, next) => {
|
|
235
|
+
if (!cloudUrl) {
|
|
236
|
+
return c.json({
|
|
237
|
+
success: false,
|
|
238
|
+
error: {
|
|
239
|
+
code: "marketplace_unavailable",
|
|
240
|
+
message: "No control-plane URL configured for this runtime (OS_CLOUD_URL)."
|
|
241
|
+
}
|
|
242
|
+
}, 503);
|
|
243
|
+
}
|
|
244
|
+
try {
|
|
245
|
+
const incomingUrl = new URL(c.req.url);
|
|
246
|
+
if (incomingUrl.pathname.startsWith(`${MARKETPLACE_PREFIX}/install-local`)) {
|
|
247
|
+
return next();
|
|
248
|
+
}
|
|
249
|
+
const method = String(c.req.method ?? "GET").toUpperCase();
|
|
250
|
+
if (publicBaseUrl && (method === "GET" || method === "HEAD")) {
|
|
251
|
+
const r2Resp = await tryPublicMarketplaceFetch(
|
|
252
|
+
publicBaseUrl,
|
|
253
|
+
incomingUrl,
|
|
254
|
+
method,
|
|
255
|
+
c.req.header("accept"),
|
|
256
|
+
ctx.logger
|
|
257
|
+
);
|
|
258
|
+
if (r2Resp) return r2Resp;
|
|
259
|
+
}
|
|
260
|
+
const target = `${cloudUrl}${incomingUrl.pathname}${incomingUrl.search}`;
|
|
261
|
+
if (method !== "GET" && method !== "HEAD") {
|
|
262
|
+
return next();
|
|
263
|
+
}
|
|
264
|
+
const accept = c.req.header("accept") ?? "application/json";
|
|
265
|
+
const acceptLang = c.req.header("accept-language") ?? "";
|
|
266
|
+
const cacheKey = `${incomingUrl.pathname}${incomingUrl.search}|al=${acceptLang}|a=${accept}`;
|
|
267
|
+
const reqCacheCtl = (c.req.header("cache-control") ?? "").toLowerCase();
|
|
268
|
+
const bypass = !cache || reqCacheCtl.includes("no-cache") || reqCacheCtl.includes("no-store");
|
|
269
|
+
const now = Date.now();
|
|
270
|
+
if (cache && !bypass) {
|
|
271
|
+
const hit = cache.get(cacheKey);
|
|
272
|
+
if (hit && hit.expiresAt > now) {
|
|
273
|
+
return buildCachedResponse(hit, method, "HIT");
|
|
274
|
+
}
|
|
275
|
+
if (hit) {
|
|
276
|
+
const revalHeaders = {
|
|
277
|
+
"Accept": accept,
|
|
278
|
+
"User-Agent": `objectos-marketplace-proxy/${_MarketplaceProxyPlugin.prototype.version ?? "1.0.0"}`
|
|
279
|
+
};
|
|
280
|
+
if (acceptLang) revalHeaders["Accept-Language"] = acceptLang;
|
|
281
|
+
if (hit.etag) revalHeaders["If-None-Match"] = hit.etag;
|
|
282
|
+
if (hit.lastModified) revalHeaders["If-Modified-Since"] = hit.lastModified;
|
|
283
|
+
const revalResp = await fetch(target, { method: "GET", headers: revalHeaders });
|
|
284
|
+
if (revalResp.status === 304) {
|
|
285
|
+
hit.expiresAt = now + hit.ttlMs;
|
|
286
|
+
const newEtag = revalResp.headers.get("etag");
|
|
287
|
+
const newLm = revalResp.headers.get("last-modified");
|
|
288
|
+
if (newEtag) hit.etag = newEtag;
|
|
289
|
+
if (newLm) hit.lastModified = newLm;
|
|
290
|
+
cache.set(cacheKey, hit);
|
|
291
|
+
return buildCachedResponse(hit, method, "REVALIDATED");
|
|
292
|
+
}
|
|
293
|
+
return await consumeAndMaybeCache(revalResp, cacheKey, incomingUrl.pathname, method, cache);
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
const reqHeaders = {
|
|
297
|
+
// Strip the inbound Host header — fetch will set
|
|
298
|
+
// it to the cloud host. Forward only the
|
|
299
|
+
// identifying headers cloud might log.
|
|
300
|
+
"Accept": accept,
|
|
301
|
+
"User-Agent": `objectos-marketplace-proxy/${_MarketplaceProxyPlugin.prototype.version ?? "1.0.0"}`
|
|
302
|
+
};
|
|
303
|
+
if (acceptLang) reqHeaders["Accept-Language"] = acceptLang;
|
|
304
|
+
const resp = await fetch(target, { method: "GET", headers: reqHeaders });
|
|
305
|
+
if (bypass || !cache) {
|
|
306
|
+
return await passthroughResponse(resp, method, bypass ? "BYPASS" : "MISS");
|
|
307
|
+
}
|
|
308
|
+
return await consumeAndMaybeCache(resp, cacheKey, incomingUrl.pathname, method, cache);
|
|
309
|
+
} catch (err) {
|
|
310
|
+
const errObj = err instanceof Error ? err : new Error(err?.message ?? String(err));
|
|
311
|
+
ctx.logger?.error?.("[MarketplaceProxyPlugin] proxy failed", errObj);
|
|
312
|
+
return c.json({
|
|
313
|
+
success: false,
|
|
314
|
+
error: {
|
|
315
|
+
code: "marketplace_proxy_failed",
|
|
316
|
+
message: err?.message ?? String(err)
|
|
317
|
+
}
|
|
318
|
+
}, 502);
|
|
319
|
+
}
|
|
320
|
+
};
|
|
321
|
+
if (typeof rawApp.all === "function") {
|
|
322
|
+
rawApp.all(`${MARKETPLACE_PREFIX}/*`, handler);
|
|
323
|
+
} else {
|
|
324
|
+
for (const m of ["get", "head"]) {
|
|
325
|
+
try {
|
|
326
|
+
rawApp[m]?.(`${MARKETPLACE_PREFIX}/*`, handler);
|
|
327
|
+
} catch {
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
ctx.logger?.info?.(`[MarketplaceProxyPlugin] mounted at ${MARKETPLACE_PREFIX}/* \u2192 ${cloudUrl || "(unconfigured)"} (cache=${this.cache ? "on" : "off"})`);
|
|
332
|
+
});
|
|
333
|
+
};
|
|
334
|
+
this.cloudUrl = resolveCloudUrl(config.controlPlaneUrl);
|
|
335
|
+
this.publicBaseUrl = resolveMarketplacePublicBaseUrl(config.publicMarketplaceBaseUrl);
|
|
336
|
+
const envFlag = (process.env.OS_MARKETPLACE_CACHE ?? "").trim().toLowerCase();
|
|
337
|
+
const envDisabled = ["off", "false", "0", "no", "disable", "disabled"].includes(envFlag);
|
|
338
|
+
const disabled = config.cacheDisabled ?? envDisabled;
|
|
339
|
+
this.cache = disabled ? null : new LruTtlCache(Math.max(8, config.cacheMaxEntries ?? DEFAULT_LRU_MAX));
|
|
340
|
+
}
|
|
341
|
+
};
|
|
342
|
+
async function tryPublicMarketplaceFetch(publicBaseUrl, incomingUrl, method, acceptHeader, logger) {
|
|
343
|
+
const key = publicMarketplaceKeyForApiPath(incomingUrl.pathname);
|
|
344
|
+
if (!key) return null;
|
|
345
|
+
const target = `${publicBaseUrl}/${key}`;
|
|
346
|
+
let resp;
|
|
347
|
+
try {
|
|
348
|
+
resp = await fetch(target, {
|
|
349
|
+
method: "GET",
|
|
350
|
+
headers: {
|
|
351
|
+
"Accept": acceptHeader || "application/json",
|
|
352
|
+
"User-Agent": `objectos-marketplace-proxy/public-r2`
|
|
353
|
+
}
|
|
354
|
+
});
|
|
355
|
+
} catch (err) {
|
|
356
|
+
logger?.warn?.(`[MarketplaceProxyPlugin] public R2 fetch failed (${target}): ${err?.message ?? err}`);
|
|
357
|
+
return null;
|
|
358
|
+
}
|
|
359
|
+
if (resp.status === 404) return null;
|
|
360
|
+
if (!resp.ok) {
|
|
361
|
+
logger?.warn?.(`[MarketplaceProxyPlugin] public R2 ${target} returned ${resp.status} \u2014 falling back to cloud`);
|
|
362
|
+
return null;
|
|
363
|
+
}
|
|
364
|
+
const isList = key === "packages.json";
|
|
365
|
+
const hasFilters = isList && (incomingUrl.searchParams.has("q") || incomingUrl.searchParams.has("category") || incomingUrl.searchParams.has("limit") || incomingUrl.searchParams.has("offset"));
|
|
366
|
+
if (!hasFilters) {
|
|
367
|
+
const headers2 = new Headers();
|
|
368
|
+
const ct = resp.headers.get("content-type") ?? "application/json; charset=utf-8";
|
|
369
|
+
headers2.set("content-type", ct);
|
|
370
|
+
const cc = resp.headers.get("cache-control");
|
|
371
|
+
if (cc) headers2.set("cache-control", cc);
|
|
372
|
+
const etag = resp.headers.get("etag");
|
|
373
|
+
if (etag) headers2.set("etag", etag);
|
|
374
|
+
headers2.set("x-cache", "PUBLIC-R2");
|
|
375
|
+
const body2 = method === "HEAD" ? null : resp.body;
|
|
376
|
+
return new Response(body2, { status: 200, headers: headers2 });
|
|
377
|
+
}
|
|
378
|
+
let snapshot;
|
|
379
|
+
try {
|
|
380
|
+
snapshot = await resp.json();
|
|
381
|
+
} catch (err) {
|
|
382
|
+
logger?.warn?.(`[MarketplaceProxyPlugin] public R2 list snapshot parse failed: ${err?.message ?? err}`);
|
|
383
|
+
return null;
|
|
384
|
+
}
|
|
385
|
+
const items = Array.isArray(snapshot?.data?.items) ? snapshot.data.items : [];
|
|
386
|
+
const q = (incomingUrl.searchParams.get("q") ?? "").trim().toLowerCase();
|
|
387
|
+
const category = (incomingUrl.searchParams.get("category") ?? "").trim();
|
|
388
|
+
const limit = Math.min(Math.max(Number(incomingUrl.searchParams.get("limit") ?? 50), 1), 100);
|
|
389
|
+
const offset = Math.max(Number(incomingUrl.searchParams.get("offset") ?? 0), 0);
|
|
390
|
+
let filtered = items;
|
|
391
|
+
if (q) {
|
|
392
|
+
filtered = filtered.filter((r) => {
|
|
393
|
+
const dn = String(r?.display_name ?? "").toLowerCase();
|
|
394
|
+
const mid = String(r?.manifest_id ?? "").toLowerCase();
|
|
395
|
+
return dn.includes(q) || mid.includes(q);
|
|
396
|
+
});
|
|
397
|
+
}
|
|
398
|
+
if (category) {
|
|
399
|
+
filtered = filtered.filter((r) => String(r?.category ?? "") === category);
|
|
400
|
+
}
|
|
401
|
+
const total = filtered.length;
|
|
402
|
+
const page = filtered.slice(offset, offset + limit);
|
|
403
|
+
const body = JSON.stringify({ success: true, data: { items: page, total, limit, offset } });
|
|
404
|
+
const headers = new Headers({
|
|
405
|
+
"content-type": "application/json; charset=utf-8",
|
|
406
|
+
"cache-control": "public, max-age=30",
|
|
407
|
+
"x-cache": "PUBLIC-R2-FILTERED"
|
|
408
|
+
});
|
|
409
|
+
return new Response(method === "HEAD" ? null : body, { status: 200, headers });
|
|
410
|
+
}
|
|
411
|
+
var PASSTHROUGH_HEADERS = ["content-type", "cache-control", "etag", "last-modified", "vary"];
|
|
412
|
+
function collectHeaders(src) {
|
|
413
|
+
const out = {};
|
|
414
|
+
for (const h of PASSTHROUGH_HEADERS) {
|
|
415
|
+
const v = src.headers.get(h);
|
|
416
|
+
if (v) out[h] = v;
|
|
417
|
+
}
|
|
418
|
+
return out;
|
|
419
|
+
}
|
|
420
|
+
function buildCachedResponse(entry, method, xCache) {
|
|
421
|
+
const headers = new Headers(entry.headers);
|
|
422
|
+
headers.set("X-Cache", xCache);
|
|
423
|
+
const ageSec = Math.max(0, Math.floor((entry.expiresAt - entry.ttlMs - Date.now()) / -1e3));
|
|
424
|
+
headers.set("Age", String(Math.max(0, ageSec)));
|
|
425
|
+
const body = method === "HEAD" ? null : entry.body;
|
|
426
|
+
return new Response(body, { status: entry.status, headers });
|
|
427
|
+
}
|
|
428
|
+
async function passthroughResponse(resp, method, xCache) {
|
|
429
|
+
const headers = new Headers(collectHeaders(resp));
|
|
430
|
+
headers.set("X-Cache", xCache);
|
|
431
|
+
if (method === "HEAD") {
|
|
432
|
+
try {
|
|
433
|
+
await resp.arrayBuffer();
|
|
434
|
+
} catch {
|
|
435
|
+
}
|
|
436
|
+
return new Response(null, { status: resp.status, headers });
|
|
437
|
+
}
|
|
438
|
+
const body = await resp.arrayBuffer();
|
|
439
|
+
return new Response(body, { status: resp.status, headers });
|
|
440
|
+
}
|
|
441
|
+
async function consumeAndMaybeCache(resp, key, pathname, method, cache) {
|
|
442
|
+
const body = await resp.arrayBuffer();
|
|
443
|
+
const headers = collectHeaders(resp);
|
|
444
|
+
if (resp.status >= 200 && resp.status < 300) {
|
|
445
|
+
const ttlMs = ttlForPath(pathname);
|
|
446
|
+
const entry = {
|
|
447
|
+
status: resp.status,
|
|
448
|
+
body,
|
|
449
|
+
headers,
|
|
450
|
+
etag: resp.headers.get("etag") ?? void 0,
|
|
451
|
+
lastModified: resp.headers.get("last-modified") ?? void 0,
|
|
452
|
+
expiresAt: Date.now() + ttlMs,
|
|
453
|
+
ttlMs
|
|
454
|
+
};
|
|
455
|
+
cache.set(key, entry);
|
|
456
|
+
}
|
|
457
|
+
const respHeaders = new Headers(headers);
|
|
458
|
+
respHeaders.set("X-Cache", "MISS");
|
|
459
|
+
const outBody = method === "HEAD" ? null : body;
|
|
460
|
+
return new Response(outBody, { status: resp.status, headers: respHeaders });
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
// src/marketplace-install-local-plugin.ts
|
|
464
|
+
var import_types = require("@objectstack/types");
|
|
465
|
+
|
|
466
|
+
// src/local-manifest-source.ts
|
|
467
|
+
var import_node_fs = require("fs");
|
|
468
|
+
var import_node_path = require("path");
|
|
469
|
+
var DEFAULT_INSTALLED_PACKAGES_DIR = ".objectstack/installed-packages";
|
|
470
|
+
function safeFilename(manifestId) {
|
|
471
|
+
return manifestId.replace(/[^a-zA-Z0-9._-]/g, "_") + ".json";
|
|
472
|
+
}
|
|
473
|
+
var LocalManifestSource = class {
|
|
474
|
+
constructor(storageDir) {
|
|
475
|
+
this.dir = storageDir ? (0, import_node_path.resolve)(storageDir) : (0, import_node_path.resolve)(process.cwd(), DEFAULT_INSTALLED_PACKAGES_DIR);
|
|
476
|
+
}
|
|
477
|
+
/** Every valid entry in the ledger (corrupt files are skipped). */
|
|
478
|
+
list() {
|
|
479
|
+
if (!(0, import_node_fs.existsSync)(this.dir)) return [];
|
|
480
|
+
const out = [];
|
|
481
|
+
for (const name of (0, import_node_fs.readdirSync)(this.dir)) {
|
|
482
|
+
if (!name.endsWith(".json")) continue;
|
|
483
|
+
try {
|
|
484
|
+
const raw = (0, import_node_fs.readFileSync)((0, import_node_path.join)(this.dir, name), "utf8");
|
|
485
|
+
out.push(JSON.parse(raw));
|
|
486
|
+
} catch {
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
return out;
|
|
490
|
+
}
|
|
491
|
+
/** Read one entry; null when absent or unreadable. */
|
|
492
|
+
read(manifestId) {
|
|
493
|
+
const file = this.fileFor(manifestId);
|
|
494
|
+
if (!(0, import_node_fs.existsSync)(file)) return null;
|
|
495
|
+
try {
|
|
496
|
+
return JSON.parse((0, import_node_fs.readFileSync)(file, "utf8"));
|
|
497
|
+
} catch {
|
|
498
|
+
return null;
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
/** Whether the ledger holds an entry for this manifest id. */
|
|
502
|
+
has(manifestId) {
|
|
503
|
+
return (0, import_node_fs.existsSync)(this.fileFor(manifestId));
|
|
504
|
+
}
|
|
505
|
+
/** Create or replace an entry (upsert by manifestId). */
|
|
506
|
+
write(entry) {
|
|
507
|
+
(0, import_node_fs.mkdirSync)(this.dir, { recursive: true });
|
|
508
|
+
(0, import_node_fs.writeFileSync)(this.fileFor(entry.manifestId), JSON.stringify(entry, null, 2), "utf8");
|
|
509
|
+
}
|
|
510
|
+
/** Remove an entry. Returns false when it was not present. */
|
|
511
|
+
remove(manifestId) {
|
|
512
|
+
const file = this.fileFor(manifestId);
|
|
513
|
+
if (!(0, import_node_fs.existsSync)(file)) return false;
|
|
514
|
+
(0, import_node_fs.unlinkSync)(file);
|
|
515
|
+
return true;
|
|
516
|
+
}
|
|
517
|
+
fileFor(manifestId) {
|
|
518
|
+
return (0, import_node_path.join)(this.dir, safeFilename(manifestId));
|
|
519
|
+
}
|
|
520
|
+
};
|
|
521
|
+
|
|
522
|
+
// src/connection-credential-store.ts
|
|
523
|
+
var import_node_fs2 = require("fs");
|
|
524
|
+
var import_node_path2 = require("path");
|
|
525
|
+
var DEFAULT_CONNECTION_CREDENTIAL_PATH = ".objectstack/cloud-connection.json";
|
|
526
|
+
var ConnectionCredentialStore = class {
|
|
527
|
+
constructor(path) {
|
|
528
|
+
this.path = path ? (0, import_node_path2.resolve)(path) : (0, import_node_path2.resolve)(process.cwd(), DEFAULT_CONNECTION_CREDENTIAL_PATH);
|
|
529
|
+
}
|
|
530
|
+
/**
|
|
531
|
+
* Read the stored credential; null when absent or unreadable.
|
|
532
|
+
*
|
|
533
|
+
* An IDENTITY RESIDUAL — `runtimeToken: ''` with a `runtimeId` — is a
|
|
534
|
+
* valid record: unbind leaves one behind so a later re-bind to the same
|
|
535
|
+
* org claims the same registration (ADR runtime-identity-binding §2.1).
|
|
536
|
+
* Callers already treat the empty token as "no credential".
|
|
537
|
+
*/
|
|
538
|
+
read() {
|
|
539
|
+
if (!(0, import_node_fs2.existsSync)(this.path)) return null;
|
|
540
|
+
try {
|
|
541
|
+
const parsed = JSON.parse((0, import_node_fs2.readFileSync)(this.path, "utf8"));
|
|
542
|
+
if (!parsed || typeof parsed.runtimeToken !== "string") return null;
|
|
543
|
+
if (!parsed.runtimeToken && !(typeof parsed.runtimeId === "string" && parsed.runtimeId)) return null;
|
|
544
|
+
return parsed;
|
|
545
|
+
} catch {
|
|
546
|
+
return null;
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
/** Persist (replace) the credential. Written 0600 — it is a secret. */
|
|
550
|
+
write(credential) {
|
|
551
|
+
(0, import_node_fs2.mkdirSync)((0, import_node_path2.dirname)(this.path), { recursive: true });
|
|
552
|
+
(0, import_node_fs2.writeFileSync)(this.path, JSON.stringify(credential, null, 2), { encoding: "utf8", mode: 384 });
|
|
553
|
+
}
|
|
554
|
+
/** Remove the credential (unbind). Returns false when nothing was stored. */
|
|
555
|
+
clear() {
|
|
556
|
+
if (!(0, import_node_fs2.existsSync)(this.path)) return false;
|
|
557
|
+
(0, import_node_fs2.unlinkSync)(this.path);
|
|
558
|
+
return true;
|
|
559
|
+
}
|
|
560
|
+
};
|
|
561
|
+
|
|
562
|
+
// src/marketplace-install-local-plugin.ts
|
|
563
|
+
var ROUTE_BASE = "/api/v1/marketplace/install-local";
|
|
564
|
+
var MarketplaceInstallLocalPlugin = class {
|
|
565
|
+
constructor(config = {}) {
|
|
566
|
+
this.name = "com.objectstack.runtime.marketplace-install-local";
|
|
567
|
+
this.version = "1.0.0";
|
|
568
|
+
this.init = async (_ctx) => {
|
|
569
|
+
};
|
|
570
|
+
this.start = async (ctx) => {
|
|
571
|
+
ctx.hook("kernel:ready", async () => {
|
|
572
|
+
try {
|
|
573
|
+
const manifest = ctx.getService("manifest");
|
|
574
|
+
manifest?.register?.(MARKETPLACE_INSTALLED_UI_BUNDLE);
|
|
575
|
+
} catch {
|
|
576
|
+
}
|
|
577
|
+
await this.rehydrate(ctx);
|
|
578
|
+
let httpServer;
|
|
579
|
+
try {
|
|
580
|
+
httpServer = ctx.getService("http-server");
|
|
581
|
+
} catch {
|
|
582
|
+
ctx.logger?.warn?.("[MarketplaceInstallLocal] http-server not available \u2014 install endpoints not mounted");
|
|
583
|
+
return;
|
|
584
|
+
}
|
|
585
|
+
if (!httpServer || typeof httpServer.getRawApp !== "function") {
|
|
586
|
+
ctx.logger?.warn?.("[MarketplaceInstallLocal] http-server missing getRawApp() \u2014 install endpoints not mounted");
|
|
587
|
+
return;
|
|
588
|
+
}
|
|
589
|
+
const rawApp = httpServer.getRawApp();
|
|
590
|
+
const postHandler = async (c) => this.handleInstall(c, ctx);
|
|
591
|
+
const getHandler = async (c) => this.handleList(c);
|
|
592
|
+
const deleteHandler = async (c) => this.handleUninstall(c, ctx);
|
|
593
|
+
const reseedHandler = async (c) => this.handleReseed(c, ctx);
|
|
594
|
+
const purgeHandler = async (c) => this.handlePurge(c, ctx);
|
|
595
|
+
if (typeof rawApp.post === "function") rawApp.post(ROUTE_BASE, postHandler);
|
|
596
|
+
if (typeof rawApp.get === "function") rawApp.get(ROUTE_BASE, getHandler);
|
|
597
|
+
if (typeof rawApp.delete === "function") rawApp.delete(`${ROUTE_BASE}/:manifestId`, deleteHandler);
|
|
598
|
+
if (typeof rawApp.post === "function") {
|
|
599
|
+
rawApp.post(`${ROUTE_BASE}/:manifestId/reseed-sample-data`, reseedHandler);
|
|
600
|
+
rawApp.post(`${ROUTE_BASE}/:manifestId/purge-sample-data`, purgeHandler);
|
|
601
|
+
}
|
|
602
|
+
ctx.logger?.info?.(`[MarketplaceInstallLocal] mounted at ${ROUTE_BASE} (storage: ${this.storageDir})`);
|
|
603
|
+
});
|
|
604
|
+
};
|
|
605
|
+
/**
|
|
606
|
+
* Re-register every cached manifest with the kernel's manifest service.
|
|
607
|
+
* Safe to call on a kernel that already has the same manifest_id (the
|
|
608
|
+
* underlying ObjectQL registry overwrites by id, but we still warn so
|
|
609
|
+
* a developer can spot the dev-time clash between their config.ts and
|
|
610
|
+
* a marketplace package).
|
|
611
|
+
*/
|
|
612
|
+
this.rehydrate = async (ctx) => {
|
|
613
|
+
const entries = this.readAll();
|
|
614
|
+
if (entries.length === 0) return;
|
|
615
|
+
let manifestService = null;
|
|
616
|
+
try {
|
|
617
|
+
manifestService = ctx.getService("manifest");
|
|
618
|
+
} catch {
|
|
619
|
+
ctx.logger?.warn?.("[MarketplaceInstallLocal] no `manifest` service \u2014 rehydrate skipped");
|
|
620
|
+
return;
|
|
621
|
+
}
|
|
622
|
+
for (const entry of entries) {
|
|
623
|
+
try {
|
|
624
|
+
manifestService.register(entry.manifest);
|
|
625
|
+
try {
|
|
626
|
+
const ql = ctx.getService("objectql");
|
|
627
|
+
if (ql && typeof ql.syncSchemas === "function") await ql.syncSchemas();
|
|
628
|
+
} catch {
|
|
629
|
+
}
|
|
630
|
+
await this.applySideEffects(ctx, entry.manifest, { seedNow: false });
|
|
631
|
+
ctx.logger?.info?.(`[MarketplaceInstallLocal] rehydrated ${entry.manifestId}@${entry.version}`);
|
|
632
|
+
} catch (err) {
|
|
633
|
+
ctx.logger?.error?.(`[MarketplaceInstallLocal] rehydrate failed for ${entry.manifestId}`, err instanceof Error ? err : new Error(String(err)));
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
};
|
|
637
|
+
this.handleInstall = async (c, ctx) => {
|
|
638
|
+
const userId = await this.requireAuthenticatedUser(c, ctx);
|
|
639
|
+
if (!userId) {
|
|
640
|
+
return c.json({ success: false, error: { code: "unauthorized", message: "Authentication required to install packages." } }, 401);
|
|
641
|
+
}
|
|
642
|
+
let body = {};
|
|
643
|
+
try {
|
|
644
|
+
body = await c.req.json();
|
|
645
|
+
} catch {
|
|
646
|
+
}
|
|
647
|
+
const inlineManifest = body?.manifest && typeof body.manifest === "object" ? body.manifest : null;
|
|
648
|
+
const normalizeBundle = (m) => {
|
|
649
|
+
if (m && !m.id && !m.name && m.manifest && typeof m.manifest === "object" && (m.manifest.id || m.manifest.name)) {
|
|
650
|
+
const { manifest: meta, ...sections } = m;
|
|
651
|
+
return { ...meta, ...sections };
|
|
652
|
+
}
|
|
653
|
+
return m;
|
|
654
|
+
};
|
|
655
|
+
let manifest;
|
|
656
|
+
let resolvedVersionId;
|
|
657
|
+
let version;
|
|
658
|
+
let packageId;
|
|
659
|
+
if (inlineManifest) {
|
|
660
|
+
manifest = normalizeBundle(inlineManifest);
|
|
661
|
+
packageId = String(manifest.id ?? manifest.name ?? "").trim();
|
|
662
|
+
version = String(manifest.version ?? "unknown");
|
|
663
|
+
resolvedVersionId = String(body?.versionId ?? version);
|
|
664
|
+
if (!packageId) {
|
|
665
|
+
return c.json({ success: false, error: { code: "invalid_manifest", message: 'Inline manifest must have an "id" or "name".' } }, 400);
|
|
666
|
+
}
|
|
667
|
+
} else {
|
|
668
|
+
if (!this.cloudUrl) {
|
|
669
|
+
return c.json({ success: false, error: { code: "marketplace_unavailable", message: "OS_CLOUD_URL not configured." } }, 503);
|
|
670
|
+
}
|
|
671
|
+
packageId = String(body?.packageId ?? "").trim();
|
|
672
|
+
const versionId = String(body?.versionId ?? "latest").trim() || "latest";
|
|
673
|
+
if (!packageId) {
|
|
674
|
+
return c.json({ success: false, error: { code: "bad_request", message: "packageId is required." } }, 400);
|
|
675
|
+
}
|
|
676
|
+
let payload;
|
|
677
|
+
const publicBase = resolveMarketplacePublicBaseUrl();
|
|
678
|
+
const fetchAttempts = [];
|
|
679
|
+
if (publicBase) {
|
|
680
|
+
fetchAttempts.push({
|
|
681
|
+
label: "public-r2",
|
|
682
|
+
url: `${publicBase}/packages/${encodeURIComponent(packageId)}/versions/${encodeURIComponent(versionId)}/manifest.json`
|
|
683
|
+
});
|
|
684
|
+
}
|
|
685
|
+
fetchAttempts.push({
|
|
686
|
+
label: "cloud",
|
|
687
|
+
url: `${this.cloudUrl}/api/v1/marketplace/packages/${encodeURIComponent(packageId)}/versions/${encodeURIComponent(versionId)}/manifest`
|
|
688
|
+
});
|
|
689
|
+
const cloudCredential = (process.env.OS_CLOUD_API_KEY ?? "").trim() || this.credentials.read()?.runtimeToken || "";
|
|
690
|
+
let lastErrStatus = 0;
|
|
691
|
+
let lastErrText = "";
|
|
692
|
+
for (const attempt of fetchAttempts) {
|
|
693
|
+
try {
|
|
694
|
+
const headers = { Accept: "application/json" };
|
|
695
|
+
if (attempt.label === "cloud" && cloudCredential) headers.Authorization = `Bearer ${cloudCredential}`;
|
|
696
|
+
const resp = await fetch(attempt.url, { headers });
|
|
697
|
+
if (!resp.ok) {
|
|
698
|
+
lastErrStatus = resp.status;
|
|
699
|
+
lastErrText = (await resp.text().catch(() => "")).slice(0, 200);
|
|
700
|
+
if (attempt.label === "public-r2" && resp.status === 404) {
|
|
701
|
+
ctx.logger?.info?.(`[MarketplaceInstallLocal] public-r2 miss for ${packageId}@${versionId}, falling back to cloud`);
|
|
702
|
+
continue;
|
|
703
|
+
}
|
|
704
|
+
if (attempt.label === "public-r2" && resp.status >= 500) {
|
|
705
|
+
ctx.logger?.warn?.(`[MarketplaceInstallLocal] public-r2 ${resp.status}, falling back to cloud`);
|
|
706
|
+
continue;
|
|
707
|
+
}
|
|
708
|
+
break;
|
|
709
|
+
}
|
|
710
|
+
payload = await resp.json();
|
|
711
|
+
lastErrStatus = 0;
|
|
712
|
+
break;
|
|
713
|
+
} catch (err) {
|
|
714
|
+
if (attempt.label === "public-r2") {
|
|
715
|
+
ctx.logger?.warn?.(`[MarketplaceInstallLocal] public-r2 fetch error: ${err?.message ?? err}, falling back to cloud`);
|
|
716
|
+
continue;
|
|
717
|
+
}
|
|
718
|
+
return c.json({
|
|
719
|
+
success: false,
|
|
720
|
+
error: { code: "cloud_fetch_failed", message: err?.message ?? String(err) }
|
|
721
|
+
}, 502);
|
|
722
|
+
}
|
|
723
|
+
}
|
|
724
|
+
if (!payload) {
|
|
725
|
+
return c.json({
|
|
726
|
+
success: false,
|
|
727
|
+
error: { code: "cloud_fetch_failed", message: `Cloud returned ${lastErrStatus}: ${lastErrText}` }
|
|
728
|
+
}, lastErrStatus === 404 ? 404 : 502);
|
|
729
|
+
}
|
|
730
|
+
const data = payload?.data ?? payload;
|
|
731
|
+
manifest = normalizeBundle(data?.manifest);
|
|
732
|
+
resolvedVersionId = String(data?.version_id ?? versionId);
|
|
733
|
+
version = String(data?.version ?? "unknown");
|
|
734
|
+
}
|
|
735
|
+
const manifestId = String(manifest?.id ?? manifest?.name ?? "");
|
|
736
|
+
if (!manifest || !manifestId) {
|
|
737
|
+
return c.json({ success: false, error: { code: "invalid_manifest", message: "Invalid manifest payload." } }, inlineManifest ? 400 : 502);
|
|
738
|
+
}
|
|
739
|
+
const conflict = this.findConflict(ctx, manifestId);
|
|
740
|
+
if (conflict === "user-code") {
|
|
741
|
+
return c.json({
|
|
742
|
+
success: false,
|
|
743
|
+
error: {
|
|
744
|
+
code: "manifest_conflict",
|
|
745
|
+
message: `manifest_id "${manifestId}" is already defined by this runtime's local code. Refusing to overwrite. Uninstall the local definition first.`
|
|
746
|
+
}
|
|
747
|
+
}, 409);
|
|
748
|
+
}
|
|
749
|
+
try {
|
|
750
|
+
const manifestService = ctx.getService("manifest");
|
|
751
|
+
manifestService.register(manifest);
|
|
752
|
+
} catch (err) {
|
|
753
|
+
if (inlineManifest) {
|
|
754
|
+
return c.json({
|
|
755
|
+
success: false,
|
|
756
|
+
error: { code: "register_failed", message: `Failed to register imported manifest: ${err?.message ?? err}` }
|
|
757
|
+
}, 422);
|
|
758
|
+
}
|
|
759
|
+
ctx.logger?.warn?.(`[MarketplaceInstallLocal] hot-register failed for ${manifestId} (will load on next restart): ${err?.message ?? err}`);
|
|
760
|
+
}
|
|
761
|
+
const entry = {
|
|
762
|
+
packageId,
|
|
763
|
+
versionId: resolvedVersionId,
|
|
764
|
+
manifestId,
|
|
765
|
+
version,
|
|
766
|
+
manifest,
|
|
767
|
+
installedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
768
|
+
installedBy: userId,
|
|
769
|
+
withSampleData: false
|
|
770
|
+
};
|
|
771
|
+
try {
|
|
772
|
+
this.ledger.write(entry);
|
|
773
|
+
} catch (err) {
|
|
774
|
+
return c.json({
|
|
775
|
+
success: false,
|
|
776
|
+
error: { code: "storage_failed", message: `Failed to persist manifest: ${err?.message ?? err}` }
|
|
777
|
+
}, 500);
|
|
778
|
+
}
|
|
779
|
+
try {
|
|
780
|
+
const ql = ctx.getService("objectql");
|
|
781
|
+
if (ql && typeof ql.syncSchemas === "function") {
|
|
782
|
+
await ql.syncSchemas();
|
|
783
|
+
ctx.logger?.info?.(`[MarketplaceInstallLocal] syncSchemas() ran after registering ${manifestId}`);
|
|
784
|
+
}
|
|
785
|
+
} catch (err) {
|
|
786
|
+
ctx.logger?.warn?.(`[MarketplaceInstallLocal] syncSchemas failed for ${manifestId}: ${err?.message ?? err}`);
|
|
787
|
+
}
|
|
788
|
+
const seededSummary = await this.applySideEffects(ctx, manifest, { seedNow: true, c });
|
|
789
|
+
if (seededSummary.seeded.mode === "inline" && (seededSummary.seeded.inserted ?? 0) + (seededSummary.seeded.updated ?? 0) > 0) {
|
|
790
|
+
entry.withSampleData = true;
|
|
791
|
+
try {
|
|
792
|
+
this.ledger.write(entry);
|
|
793
|
+
} catch {
|
|
794
|
+
}
|
|
795
|
+
}
|
|
796
|
+
return c.json({
|
|
797
|
+
success: true,
|
|
798
|
+
data: {
|
|
799
|
+
manifestId,
|
|
800
|
+
version,
|
|
801
|
+
versionId: resolvedVersionId,
|
|
802
|
+
installedAt: entry.installedAt,
|
|
803
|
+
hotLoaded: true,
|
|
804
|
+
upgradedFrom: conflict === "marketplace" ? "previous-marketplace-version" : null,
|
|
805
|
+
translationsLoaded: seededSummary.translationsLoaded,
|
|
806
|
+
seeded: seededSummary.seeded,
|
|
807
|
+
note: "App is now available in this runtime. Refresh the console to see it in the app switcher."
|
|
808
|
+
}
|
|
809
|
+
}, 200);
|
|
810
|
+
};
|
|
811
|
+
this.handleList = async (c) => {
|
|
812
|
+
const entries = this.readAll();
|
|
813
|
+
return c.json({
|
|
814
|
+
success: true,
|
|
815
|
+
data: {
|
|
816
|
+
items: entries.map((e) => ({
|
|
817
|
+
packageId: e.packageId,
|
|
818
|
+
versionId: e.versionId,
|
|
819
|
+
manifestId: e.manifestId,
|
|
820
|
+
version: e.version,
|
|
821
|
+
installedAt: e.installedAt,
|
|
822
|
+
installedBy: e.installedBy,
|
|
823
|
+
withSampleData: e.withSampleData ?? false
|
|
824
|
+
})),
|
|
825
|
+
total: entries.length,
|
|
826
|
+
storageDir: this.storageDir
|
|
827
|
+
}
|
|
828
|
+
}, 200);
|
|
829
|
+
};
|
|
830
|
+
this.handleUninstall = async (c, ctx) => {
|
|
831
|
+
const userId = await this.requireAuthenticatedUser(c, ctx);
|
|
832
|
+
if (!userId) {
|
|
833
|
+
return c.json({ success: false, error: { code: "unauthorized", message: "Authentication required." } }, 401);
|
|
834
|
+
}
|
|
835
|
+
const manifestId = String(c.req.param?.("manifestId") ?? c.req.params?.manifestId ?? "").trim();
|
|
836
|
+
if (!manifestId) {
|
|
837
|
+
return c.json({ success: false, error: { code: "bad_request", message: "manifestId path param required." } }, 400);
|
|
838
|
+
}
|
|
839
|
+
if (!this.ledger.has(manifestId)) {
|
|
840
|
+
return c.json({ success: false, error: { code: "not_found", message: `No marketplace install for ${manifestId}.` } }, 404);
|
|
841
|
+
}
|
|
842
|
+
try {
|
|
843
|
+
this.ledger.remove(manifestId);
|
|
844
|
+
} catch (err) {
|
|
845
|
+
return c.json({ success: false, error: { code: "storage_failed", message: err?.message ?? String(err) } }, 500);
|
|
846
|
+
}
|
|
847
|
+
ctx.logger?.info?.(`[MarketplaceInstallLocal] uninstalled ${manifestId} (cached manifest removed; restart runtime to unload from running kernel)`);
|
|
848
|
+
return c.json({
|
|
849
|
+
success: true,
|
|
850
|
+
data: {
|
|
851
|
+
manifestId,
|
|
852
|
+
note: "Cached manifest removed. The app remains loaded in the running kernel until the next restart (the kernel API does not support unregistering apps in-place)."
|
|
853
|
+
}
|
|
854
|
+
}, 200);
|
|
855
|
+
};
|
|
856
|
+
/**
|
|
857
|
+
* Detect whether `manifestId` is already known to the kernel and classify
|
|
858
|
+
* the source so we can refuse vs upgrade gracefully.
|
|
859
|
+
*
|
|
860
|
+
* 'none' — fresh install
|
|
861
|
+
* 'marketplace' — previously installed by this plugin (allow upgrade)
|
|
862
|
+
* 'user-code' — defined by AppPlugin from objectstack.config.ts
|
|
863
|
+
* (refuse to avoid silently overwriting authored code)
|
|
864
|
+
*/
|
|
865
|
+
this.findConflict = (ctx, manifestId) => {
|
|
866
|
+
if (this.ledger.has(manifestId)) {
|
|
867
|
+
return "marketplace";
|
|
868
|
+
}
|
|
869
|
+
try {
|
|
870
|
+
const ql = ctx.getService("objectql");
|
|
871
|
+
const packages = ql?.registry?.getAllPackages?.() ?? [];
|
|
872
|
+
const hit = packages.find(
|
|
873
|
+
(p) => (p?.manifest?.id ?? p?.id ?? p?.manifest?.name) === manifestId
|
|
874
|
+
);
|
|
875
|
+
if (hit) return "user-code";
|
|
876
|
+
} catch {
|
|
877
|
+
}
|
|
878
|
+
return "none";
|
|
879
|
+
};
|
|
880
|
+
/**
|
|
881
|
+
* Pull a userId out of the request's better-auth session, if any.
|
|
882
|
+
* Returns null when there is no signed-in user. v1 does not check
|
|
883
|
+
* admin role — UI gating + the auth requirement is sufficient for
|
|
884
|
+
* dev / single-tenant runtimes. Stricter checks can be layered on
|
|
885
|
+
* via a middleware in cloud-hosted multi-tenant deployments.
|
|
886
|
+
*/
|
|
887
|
+
/**
|
|
888
|
+
* POST /api/v1/marketplace/install-local/:manifestId/reseed-sample-data
|
|
889
|
+
*
|
|
890
|
+
* Re-runs SeedLoaderService against the cached manifest's `data` arrays.
|
|
891
|
+
* Idempotent (upsert by id). Useful when:
|
|
892
|
+
* • The user installed an app and skipped sample data
|
|
893
|
+
* • A purge was undone
|
|
894
|
+
* • The user wants a clean baseline back after editing demo rows
|
|
895
|
+
*
|
|
896
|
+
* Multi-tenant: requires an active organization on the session (same
|
|
897
|
+
* rule as install seed path).
|
|
898
|
+
*/
|
|
899
|
+
this.handleReseed = async (c, ctx) => {
|
|
900
|
+
const userId = await this.requireAuthenticatedUser(c, ctx);
|
|
901
|
+
if (!userId) {
|
|
902
|
+
return c.json({ success: false, error: { code: "unauthorized", message: "Authentication required." } }, 401);
|
|
903
|
+
}
|
|
904
|
+
const manifestId = String(c.req.param?.("manifestId") ?? c.req.params?.manifestId ?? "").trim();
|
|
905
|
+
if (!manifestId) {
|
|
906
|
+
return c.json({ success: false, error: { code: "bad_request", message: "manifestId path param required." } }, 400);
|
|
907
|
+
}
|
|
908
|
+
if (!this.ledger.has(manifestId)) {
|
|
909
|
+
return c.json({ success: false, error: { code: "not_found", message: `No marketplace install for ${manifestId}.` } }, 404);
|
|
910
|
+
}
|
|
911
|
+
const entry = this.ledger.read(manifestId);
|
|
912
|
+
if (!entry) {
|
|
913
|
+
return c.json({ success: false, error: { code: "storage_failed", message: "Failed to read manifest cache." } }, 500);
|
|
914
|
+
}
|
|
915
|
+
const summary = await this.applySideEffects(ctx, entry.manifest, { seedNow: true, c });
|
|
916
|
+
if (summary.seeded.mode === "skipped") {
|
|
917
|
+
return c.json({
|
|
918
|
+
success: false,
|
|
919
|
+
error: {
|
|
920
|
+
code: "reseed_skipped",
|
|
921
|
+
message: `Reseed did not run: ${summary.seeded.reason ?? "unknown reason"}`
|
|
922
|
+
}
|
|
923
|
+
}, 400);
|
|
924
|
+
}
|
|
925
|
+
try {
|
|
926
|
+
entry.withSampleData = true;
|
|
927
|
+
this.ledger.write(entry);
|
|
928
|
+
} catch {
|
|
929
|
+
}
|
|
930
|
+
return c.json({
|
|
931
|
+
success: true,
|
|
932
|
+
data: {
|
|
933
|
+
manifestId,
|
|
934
|
+
inserted: summary.seeded.inserted ?? 0,
|
|
935
|
+
updated: summary.seeded.updated ?? 0,
|
|
936
|
+
errors: summary.seeded.errors ?? 0,
|
|
937
|
+
withSampleData: true
|
|
938
|
+
}
|
|
939
|
+
}, 200);
|
|
940
|
+
};
|
|
941
|
+
/**
|
|
942
|
+
* POST /api/v1/marketplace/install-local/:manifestId/purge-sample-data
|
|
943
|
+
*
|
|
944
|
+
* Deletes every record whose id is declared in the cached manifest's
|
|
945
|
+
* seed datasets. Uses the `driver` service directly to bypass ACL /
|
|
946
|
+
* lifecycle hooks (same pattern as cloud purge). User-created records
|
|
947
|
+
* are never touched — only ids declared in the package's bundled
|
|
948
|
+
* datasets are removed. Already-deleted rows count as `skipped`.
|
|
949
|
+
*/
|
|
950
|
+
this.handlePurge = async (c, ctx) => {
|
|
951
|
+
const userId = await this.requireAuthenticatedUser(c, ctx);
|
|
952
|
+
if (!userId) {
|
|
953
|
+
return c.json({ success: false, error: { code: "unauthorized", message: "Authentication required." } }, 401);
|
|
954
|
+
}
|
|
955
|
+
const manifestId = String(c.req.param?.("manifestId") ?? c.req.params?.manifestId ?? "").trim();
|
|
956
|
+
if (!manifestId) {
|
|
957
|
+
return c.json({ success: false, error: { code: "bad_request", message: "manifestId path param required." } }, 400);
|
|
958
|
+
}
|
|
959
|
+
if (!this.ledger.has(manifestId)) {
|
|
960
|
+
return c.json({ success: false, error: { code: "not_found", message: `No marketplace install for ${manifestId}.` } }, 404);
|
|
961
|
+
}
|
|
962
|
+
const entry = this.ledger.read(manifestId);
|
|
963
|
+
if (!entry) {
|
|
964
|
+
return c.json({ success: false, error: { code: "storage_failed", message: "Failed to read manifest cache." } }, 500);
|
|
965
|
+
}
|
|
966
|
+
const datasets = Array.isArray(entry.manifest?.data) ? entry.manifest.data.filter((d) => d && d.object && Array.isArray(d.records)) : [];
|
|
967
|
+
if (datasets.length === 0) {
|
|
968
|
+
return c.json({
|
|
969
|
+
success: false,
|
|
970
|
+
error: { code: "nothing_to_purge", message: "This package declares no seed datasets." }
|
|
971
|
+
}, 400);
|
|
972
|
+
}
|
|
973
|
+
let driver;
|
|
974
|
+
try {
|
|
975
|
+
driver = ctx.getService("driver");
|
|
976
|
+
} catch {
|
|
977
|
+
}
|
|
978
|
+
if (!driver || typeof driver.delete !== "function") {
|
|
979
|
+
return c.json({
|
|
980
|
+
success: false,
|
|
981
|
+
error: { code: "driver_missing", message: "driver service unavailable \u2014 cannot purge." }
|
|
982
|
+
}, 500);
|
|
983
|
+
}
|
|
984
|
+
let deleted = 0;
|
|
985
|
+
let skipped = 0;
|
|
986
|
+
let errors = 0;
|
|
987
|
+
for (const ds of datasets) {
|
|
988
|
+
const object = String(ds.object);
|
|
989
|
+
for (const rec of ds.records) {
|
|
990
|
+
const id = rec?.id;
|
|
991
|
+
if (id === void 0 || id === null || id === "") {
|
|
992
|
+
skipped++;
|
|
993
|
+
continue;
|
|
994
|
+
}
|
|
995
|
+
try {
|
|
996
|
+
const r = await driver.delete(object, id);
|
|
997
|
+
if (r === false || r === 0 || r?.deleted === 0) skipped++;
|
|
998
|
+
else deleted++;
|
|
999
|
+
} catch (err) {
|
|
1000
|
+
const msg = String(err?.message ?? err);
|
|
1001
|
+
if (/not.?found|no row/i.test(msg)) skipped++;
|
|
1002
|
+
else {
|
|
1003
|
+
errors++;
|
|
1004
|
+
ctx.logger?.warn?.(`[MarketplaceInstallLocal] purge ${object}#${id}: ${msg}`);
|
|
1005
|
+
}
|
|
1006
|
+
}
|
|
1007
|
+
}
|
|
1008
|
+
}
|
|
1009
|
+
try {
|
|
1010
|
+
entry.withSampleData = false;
|
|
1011
|
+
this.ledger.write(entry);
|
|
1012
|
+
} catch {
|
|
1013
|
+
}
|
|
1014
|
+
ctx.logger?.info?.(`[MarketplaceInstallLocal] purged ${manifestId}: deleted=${deleted} skipped=${skipped} errors=${errors}`);
|
|
1015
|
+
return c.json({
|
|
1016
|
+
success: true,
|
|
1017
|
+
data: { manifestId, deleted, skipped, errors, withSampleData: false }
|
|
1018
|
+
}, 200);
|
|
1019
|
+
};
|
|
1020
|
+
/**
|
|
1021
|
+
* Replicate the start-time side-effects that AppPlugin runs for
|
|
1022
|
+
* statically-declared apps but the `manifest` service does NOT:
|
|
1023
|
+
*
|
|
1024
|
+
* 1. Load `manifest.translations` (array of `Record<locale, data>`)
|
|
1025
|
+
* into the i18n service — auto-creating an in-memory fallback if
|
|
1026
|
+
* none is registered, matching AppPlugin's behaviour.
|
|
1027
|
+
*
|
|
1028
|
+
* 2. Merge `manifest.data` (an array of seed datasets) into the
|
|
1029
|
+
* kernel's `seed-datasets` service so SecurityPlugin's per-org
|
|
1030
|
+
* replay middleware picks them up on every future
|
|
1031
|
+
* sys_organization insert.
|
|
1032
|
+
*
|
|
1033
|
+
* 3. When `seedNow=true`, also run the seed immediately so the user
|
|
1034
|
+
* sees demo data without having to create a new org:
|
|
1035
|
+
* • single-tenant: run SeedLoaderService inline (mirrors
|
|
1036
|
+
* AppPlugin single-tenant branch)
|
|
1037
|
+
* • multi-tenant: invoke `seed-replayer` for the caller's
|
|
1038
|
+
* active org (resolved from the request session)
|
|
1039
|
+
*
|
|
1040
|
+
* Errors are logged but never thrown — install succeeds even if
|
|
1041
|
+
* post-register side-effects partially fail (the manifest itself is
|
|
1042
|
+
* already registered + cached). Returns a small summary for the
|
|
1043
|
+
* response envelope.
|
|
1044
|
+
*/
|
|
1045
|
+
this.applySideEffects = async (ctx, manifest, opts) => {
|
|
1046
|
+
const appId = String(manifest?.id ?? "unknown");
|
|
1047
|
+
let translationsLoaded = 0;
|
|
1048
|
+
let seedSummary = { mode: "skipped", reason: "no-datasets" };
|
|
1049
|
+
try {
|
|
1050
|
+
const bundles = [];
|
|
1051
|
+
if (Array.isArray(manifest?.translations)) bundles.push(...manifest.translations);
|
|
1052
|
+
if (Array.isArray(manifest?.i18n)) bundles.push(...manifest.i18n);
|
|
1053
|
+
if (bundles.length > 0) {
|
|
1054
|
+
let i18nService;
|
|
1055
|
+
try {
|
|
1056
|
+
i18nService = ctx.getService("i18n");
|
|
1057
|
+
} catch {
|
|
1058
|
+
}
|
|
1059
|
+
if (!i18nService) {
|
|
1060
|
+
try {
|
|
1061
|
+
const mod = await import("@objectstack/core");
|
|
1062
|
+
const createMemoryI18n = mod.createMemoryI18n;
|
|
1063
|
+
if (typeof createMemoryI18n === "function") {
|
|
1064
|
+
i18nService = createMemoryI18n();
|
|
1065
|
+
ctx.registerService?.("i18n", i18nService);
|
|
1066
|
+
ctx.logger?.info?.(`[MarketplaceInstallLocal] auto-registered in-memory i18n fallback for "${appId}"`);
|
|
1067
|
+
}
|
|
1068
|
+
} catch {
|
|
1069
|
+
}
|
|
1070
|
+
}
|
|
1071
|
+
if (i18nService?.loadTranslations) {
|
|
1072
|
+
for (const bundle of bundles) {
|
|
1073
|
+
for (const [locale, data] of Object.entries(bundle)) {
|
|
1074
|
+
if (data && typeof data === "object") {
|
|
1075
|
+
try {
|
|
1076
|
+
i18nService.loadTranslations(locale, data);
|
|
1077
|
+
translationsLoaded++;
|
|
1078
|
+
} catch (err) {
|
|
1079
|
+
ctx.logger?.warn?.(`[MarketplaceInstallLocal] failed to load ${appId} translations for ${locale}: ${err?.message ?? err}`);
|
|
1080
|
+
}
|
|
1081
|
+
}
|
|
1082
|
+
}
|
|
1083
|
+
}
|
|
1084
|
+
ctx.logger?.info?.(`[MarketplaceInstallLocal] loaded ${translationsLoaded} locale bundle(s) for ${appId}`);
|
|
1085
|
+
}
|
|
1086
|
+
}
|
|
1087
|
+
} catch (err) {
|
|
1088
|
+
ctx.logger?.warn?.(`[MarketplaceInstallLocal] i18n side-effect failed for ${appId}: ${err?.message ?? err}`);
|
|
1089
|
+
}
|
|
1090
|
+
const datasets = Array.isArray(manifest?.data) ? manifest.data.filter((d) => d && d.object && Array.isArray(d.records)) : [];
|
|
1091
|
+
if (datasets.length > 0) {
|
|
1092
|
+
try {
|
|
1093
|
+
const kernel = ctx.kernel;
|
|
1094
|
+
let existing = [];
|
|
1095
|
+
try {
|
|
1096
|
+
const v = kernel?.getService?.("seed-datasets");
|
|
1097
|
+
if (Array.isArray(v)) existing = v;
|
|
1098
|
+
} catch {
|
|
1099
|
+
}
|
|
1100
|
+
const merged = [...existing, ...datasets];
|
|
1101
|
+
if (kernel?.registerService) kernel.registerService("seed-datasets", merged);
|
|
1102
|
+
else ctx.registerService?.("seed-datasets", merged);
|
|
1103
|
+
ctx.logger?.info?.(`[MarketplaceInstallLocal] merged ${datasets.length} seed dataset(s) into kernel (total: ${merged.length})`);
|
|
1104
|
+
} catch (err) {
|
|
1105
|
+
ctx.logger?.warn?.(`[MarketplaceInstallLocal] failed to merge seed-datasets: ${err?.message ?? err}`);
|
|
1106
|
+
}
|
|
1107
|
+
}
|
|
1108
|
+
if (opts.seedNow && datasets.length > 0) {
|
|
1109
|
+
const multiTenant = String((0, import_types.readEnvWithDeprecation)("OS_MULTI_ORG_ENABLED", "OS_MULTI_TENANT") ?? "false").toLowerCase() !== "false";
|
|
1110
|
+
try {
|
|
1111
|
+
const ql = ctx.getService("objectql");
|
|
1112
|
+
let metadata;
|
|
1113
|
+
try {
|
|
1114
|
+
metadata = ctx.getService("metadata");
|
|
1115
|
+
} catch {
|
|
1116
|
+
}
|
|
1117
|
+
if (!ql || !metadata) {
|
|
1118
|
+
seedSummary = { mode: "skipped", reason: "objectql-or-metadata-missing" };
|
|
1119
|
+
} else {
|
|
1120
|
+
let organizationId;
|
|
1121
|
+
if (multiTenant) {
|
|
1122
|
+
const resolved = await this.resolveActiveOrgId(opts.c, ctx);
|
|
1123
|
+
if (resolved) organizationId = resolved;
|
|
1124
|
+
else {
|
|
1125
|
+
seedSummary = { mode: "skipped", reason: "multi-tenant-no-active-org" };
|
|
1126
|
+
ctx.logger?.warn?.("[MarketplaceInstallLocal] multi-tenant: no active org on request \u2014 data not seeded");
|
|
1127
|
+
}
|
|
1128
|
+
}
|
|
1129
|
+
if (!multiTenant || organizationId) {
|
|
1130
|
+
const [{ SeedLoaderService }, { SeedLoaderRequestSchema }] = await Promise.all([
|
|
1131
|
+
import("@objectstack/runtime"),
|
|
1132
|
+
import("@objectstack/spec/data")
|
|
1133
|
+
]);
|
|
1134
|
+
const seedLoader = new SeedLoaderService(ql, metadata, ctx.logger);
|
|
1135
|
+
const request = SeedLoaderRequestSchema.parse({
|
|
1136
|
+
// ADR-0036 / seed rename: the field is `seeds` (was `datasets`).
|
|
1137
|
+
seeds: datasets,
|
|
1138
|
+
config: {
|
|
1139
|
+
defaultMode: "upsert",
|
|
1140
|
+
multiPass: true,
|
|
1141
|
+
...organizationId ? { organizationId } : {}
|
|
1142
|
+
}
|
|
1143
|
+
});
|
|
1144
|
+
const result = await seedLoader.load(request);
|
|
1145
|
+
seedSummary = {
|
|
1146
|
+
mode: "inline",
|
|
1147
|
+
inserted: result.summary.totalInserted,
|
|
1148
|
+
updated: result.summary.totalUpdated,
|
|
1149
|
+
errors: result.errors.length
|
|
1150
|
+
};
|
|
1151
|
+
ctx.logger?.info?.(`[MarketplaceInstallLocal] inline seed for ${appId}${organizationId ? ` (org=${organizationId})` : ""}: inserted=${seedSummary.inserted} updated=${seedSummary.updated} errors=${seedSummary.errors}`);
|
|
1152
|
+
}
|
|
1153
|
+
}
|
|
1154
|
+
} catch (err) {
|
|
1155
|
+
seedSummary = { mode: "skipped", reason: `seed-error: ${err?.message ?? err}` };
|
|
1156
|
+
ctx.logger?.warn?.(`[MarketplaceInstallLocal] seed run failed for ${appId}: ${err?.message ?? err}`);
|
|
1157
|
+
}
|
|
1158
|
+
}
|
|
1159
|
+
return { translationsLoaded, seeded: seedSummary };
|
|
1160
|
+
};
|
|
1161
|
+
/**
|
|
1162
|
+
* Best-effort active-org resolution. Reads the better-auth session
|
|
1163
|
+
* (same path as requireAuthenticatedUser) and returns
|
|
1164
|
+
* `session.activeOrganizationId`, falling back to the user's first
|
|
1165
|
+
* org membership.
|
|
1166
|
+
*/
|
|
1167
|
+
this.resolveActiveOrgId = async (c, ctx) => {
|
|
1168
|
+
if (!c?.req?.raw?.headers) return null;
|
|
1169
|
+
try {
|
|
1170
|
+
const authService = ctx.getService("auth");
|
|
1171
|
+
let api = authService?.api;
|
|
1172
|
+
if (!api && typeof authService?.getApi === "function") api = await authService.getApi();
|
|
1173
|
+
if (!api?.getSession) return null;
|
|
1174
|
+
const session = await api.getSession({ headers: c.req.raw.headers });
|
|
1175
|
+
const direct = session?.session?.activeOrganizationId ?? session?.activeOrganizationId ?? null;
|
|
1176
|
+
if (direct) return String(direct);
|
|
1177
|
+
const userId = session?.user?.id;
|
|
1178
|
+
if (!userId) return null;
|
|
1179
|
+
try {
|
|
1180
|
+
const ql = ctx.getService("objectql");
|
|
1181
|
+
if (ql?.find) {
|
|
1182
|
+
const rows = await ql.find("sys_organization_member", { where: { user_id: userId }, limit: 1, context: { isSystem: true } });
|
|
1183
|
+
const row = Array.isArray(rows) ? rows[0] : rows?.items?.[0] ?? null;
|
|
1184
|
+
return row?.organization_id ? String(row.organization_id) : null;
|
|
1185
|
+
}
|
|
1186
|
+
} catch {
|
|
1187
|
+
}
|
|
1188
|
+
} catch {
|
|
1189
|
+
}
|
|
1190
|
+
return null;
|
|
1191
|
+
};
|
|
1192
|
+
this.requireAuthenticatedUser = async (c, ctx) => {
|
|
1193
|
+
try {
|
|
1194
|
+
const authService = ctx.getService("auth");
|
|
1195
|
+
let api = authService?.api;
|
|
1196
|
+
if (!api && typeof authService?.getApi === "function") {
|
|
1197
|
+
api = await authService.getApi();
|
|
1198
|
+
}
|
|
1199
|
+
if (api?.getSession && c?.req?.raw?.headers) {
|
|
1200
|
+
const session = await api.getSession({ headers: c.req.raw.headers });
|
|
1201
|
+
const userId = session?.user?.id ?? null;
|
|
1202
|
+
if (userId) return String(userId);
|
|
1203
|
+
}
|
|
1204
|
+
} catch {
|
|
1205
|
+
}
|
|
1206
|
+
const xUserId = c?.req?.header?.("x-user-id");
|
|
1207
|
+
if (xUserId) return String(xUserId);
|
|
1208
|
+
return null;
|
|
1209
|
+
};
|
|
1210
|
+
this.readAll = () => this.ledger.list();
|
|
1211
|
+
this.cloudUrl = resolveCloudUrl(config.controlPlaneUrl);
|
|
1212
|
+
this.ledger = new LocalManifestSource(config.storageDir);
|
|
1213
|
+
this.storageDir = this.ledger.dir;
|
|
1214
|
+
this.credentials = new ConnectionCredentialStore();
|
|
1215
|
+
}
|
|
1216
|
+
};
|
|
1217
|
+
|
|
1218
|
+
// src/cloud-connection-plugin.ts
|
|
1219
|
+
var import_node_os = require("os");
|
|
1220
|
+
|
|
1221
|
+
// src/cloud-connection-ui.ts
|
|
1222
|
+
var CloudConnectionSettingsPage = {
|
|
1223
|
+
name: "cloud_connection_settings",
|
|
1224
|
+
label: "Cloud Connection",
|
|
1225
|
+
type: "app",
|
|
1226
|
+
template: "default",
|
|
1227
|
+
kind: "full",
|
|
1228
|
+
isDefault: false,
|
|
1229
|
+
regions: [
|
|
1230
|
+
{
|
|
1231
|
+
name: "header",
|
|
1232
|
+
width: "full",
|
|
1233
|
+
components: [
|
|
1234
|
+
{
|
|
1235
|
+
type: "page:header",
|
|
1236
|
+
properties: {
|
|
1237
|
+
title: "Cloud Connection",
|
|
1238
|
+
subtitle: "Connect this runtime to an ObjectStack control plane to browse your organization's private packages and install them here.",
|
|
1239
|
+
icon: "cloud"
|
|
1240
|
+
}
|
|
1241
|
+
}
|
|
1242
|
+
]
|
|
1243
|
+
},
|
|
1244
|
+
{
|
|
1245
|
+
name: "main",
|
|
1246
|
+
width: "large",
|
|
1247
|
+
components: [
|
|
1248
|
+
{
|
|
1249
|
+
// Registered console widget — the RFC 8628 device-code
|
|
1250
|
+
// state machine (status → start → user-code display →
|
|
1251
|
+
// poll → bound / disconnect). Talks to the same-origin
|
|
1252
|
+
// /api/v1/cloud-connection/* routes this plugin mounts.
|
|
1253
|
+
type: "cloud-connection:panel",
|
|
1254
|
+
properties: {}
|
|
1255
|
+
}
|
|
1256
|
+
]
|
|
1257
|
+
}
|
|
1258
|
+
]
|
|
1259
|
+
};
|
|
1260
|
+
var CLOUD_CONNECTION_NAV_CONTRIBUTIONS = [
|
|
1261
|
+
{
|
|
1262
|
+
app: "setup",
|
|
1263
|
+
group: "group_apps",
|
|
1264
|
+
priority: 200,
|
|
1265
|
+
items: [
|
|
1266
|
+
{
|
|
1267
|
+
id: "nav_cloud_connection",
|
|
1268
|
+
type: "page",
|
|
1269
|
+
pageName: "cloud_connection_settings",
|
|
1270
|
+
label: "Cloud Connection",
|
|
1271
|
+
icon: "cloud"
|
|
1272
|
+
}
|
|
1273
|
+
]
|
|
1274
|
+
}
|
|
1275
|
+
];
|
|
1276
|
+
var CLOUD_CONNECTION_UI_BUNDLE = {
|
|
1277
|
+
id: "com.objectstack.cloud-connection.ui",
|
|
1278
|
+
namespace: "sys",
|
|
1279
|
+
version: "0.1.0",
|
|
1280
|
+
type: "plugin",
|
|
1281
|
+
scope: "system",
|
|
1282
|
+
name: "Cloud Connection UI",
|
|
1283
|
+
description: "Setup page + navigation for binding this runtime to a control plane.",
|
|
1284
|
+
pages: [CloudConnectionSettingsPage],
|
|
1285
|
+
navigationContributions: CLOUD_CONNECTION_NAV_CONTRIBUTIONS
|
|
1286
|
+
};
|
|
1287
|
+
|
|
1288
|
+
// src/cloud-connection-plugin.ts
|
|
1289
|
+
var CLOUD_CONNECTION_PREFIX = "/api/v1/cloud-connection";
|
|
1290
|
+
var CloudConnectionPlugin = class {
|
|
1291
|
+
constructor(config = {}) {
|
|
1292
|
+
this.name = "com.objectstack.cloud.connection";
|
|
1293
|
+
this.version = "0.3.0";
|
|
1294
|
+
this.init = async (_ctx) => {
|
|
1295
|
+
};
|
|
1296
|
+
this.start = async (ctx) => {
|
|
1297
|
+
ctx.hook("kernel:ready", async () => {
|
|
1298
|
+
const httpServer = (() => {
|
|
1299
|
+
try {
|
|
1300
|
+
return ctx.getService("http-server");
|
|
1301
|
+
} catch {
|
|
1302
|
+
return void 0;
|
|
1303
|
+
}
|
|
1304
|
+
})();
|
|
1305
|
+
if (!httpServer || typeof httpServer.getRawApp !== "function") {
|
|
1306
|
+
ctx.logger?.warn?.("[CloudConnectionPlugin] http-server unavailable \u2014 routes not mounted");
|
|
1307
|
+
return;
|
|
1308
|
+
}
|
|
1309
|
+
const rawApp = httpServer.getRawApp();
|
|
1310
|
+
const cloudUrl = (this.cfg.controlPlaneUrl ?? process.env.OS_CLOUD_URL ?? "").trim().replace(/\/+$/, "");
|
|
1311
|
+
const cloudApiKey = (this.cfg.controlPlaneApiKey ?? process.env.OS_CLOUD_API_KEY ?? "").trim();
|
|
1312
|
+
const deviceClientId = (this.cfg.deviceClientId ?? process.env.OS_CLI_CLIENT_ID ?? "objectstack-cli").trim();
|
|
1313
|
+
const deviceScope = "openid profile email";
|
|
1314
|
+
const credential = () => cloudApiKey || this.store.read()?.runtimeToken || "";
|
|
1315
|
+
const authHeaders = () => {
|
|
1316
|
+
const cred = credential();
|
|
1317
|
+
return cred ? { Authorization: `Bearer ${cred}` } : {};
|
|
1318
|
+
};
|
|
1319
|
+
const hostOf = (c) => {
|
|
1320
|
+
try {
|
|
1321
|
+
return new URL(c.req.url).hostname;
|
|
1322
|
+
} catch {
|
|
1323
|
+
return "";
|
|
1324
|
+
}
|
|
1325
|
+
};
|
|
1326
|
+
const resolveEnvironmentId = async (c) => {
|
|
1327
|
+
const fixed = (this.cfg.environmentId ?? process.env.OS_ENVIRONMENT_ID ?? "").trim();
|
|
1328
|
+
if (fixed && fixed !== "env_local" && fixed !== "proj_local") return fixed;
|
|
1329
|
+
if (this.cfg.singleEnvironment) {
|
|
1330
|
+
return this.store.read()?.environmentId || void 0;
|
|
1331
|
+
}
|
|
1332
|
+
try {
|
|
1333
|
+
const envRegistry = ctx.getService("env-registry");
|
|
1334
|
+
const env = await envRegistry?.resolveByHostname?.(hostOf(c));
|
|
1335
|
+
return env?.environmentId;
|
|
1336
|
+
} catch {
|
|
1337
|
+
return void 0;
|
|
1338
|
+
}
|
|
1339
|
+
};
|
|
1340
|
+
try {
|
|
1341
|
+
const manifest = ctx.getService("manifest");
|
|
1342
|
+
manifest?.register?.(CLOUD_CONNECTION_UI_BUNDLE);
|
|
1343
|
+
} catch {
|
|
1344
|
+
}
|
|
1345
|
+
const sessionFromAuthService = async (authSvc, rawReq) => {
|
|
1346
|
+
const api = typeof authSvc?.getApi === "function" ? await authSvc.getApi() : authSvc?.api ?? authSvc;
|
|
1347
|
+
const session = await api?.getSession?.({ headers: rawReq.headers });
|
|
1348
|
+
const userId = session?.user?.id ? String(session.user.id) : void 0;
|
|
1349
|
+
return userId ? { userId } : null;
|
|
1350
|
+
};
|
|
1351
|
+
const resolveSession = async (environmentId, rawReq) => {
|
|
1352
|
+
try {
|
|
1353
|
+
if (this.cfg.singleEnvironment) {
|
|
1354
|
+
let authSvc2;
|
|
1355
|
+
try {
|
|
1356
|
+
authSvc2 = ctx.getService("auth");
|
|
1357
|
+
} catch {
|
|
1358
|
+
}
|
|
1359
|
+
if (!authSvc2) return null;
|
|
1360
|
+
return await sessionFromAuthService(authSvc2, rawReq);
|
|
1361
|
+
}
|
|
1362
|
+
const kernelManager = ctx.getService("kernel-manager");
|
|
1363
|
+
const kernel = await kernelManager?.getOrCreate?.(environmentId);
|
|
1364
|
+
let authSvc;
|
|
1365
|
+
try {
|
|
1366
|
+
authSvc = await kernel?.getServiceAsync?.("auth");
|
|
1367
|
+
} catch {
|
|
1368
|
+
}
|
|
1369
|
+
if (!authSvc) {
|
|
1370
|
+
try {
|
|
1371
|
+
authSvc = kernel?.getService?.("auth");
|
|
1372
|
+
} catch {
|
|
1373
|
+
}
|
|
1374
|
+
}
|
|
1375
|
+
if (!authSvc) return null;
|
|
1376
|
+
return await sessionFromAuthService(authSvc, rawReq);
|
|
1377
|
+
} catch {
|
|
1378
|
+
return null;
|
|
1379
|
+
}
|
|
1380
|
+
};
|
|
1381
|
+
rawApp.get(`${CLOUD_CONNECTION_PREFIX}/status`, async (c) => {
|
|
1382
|
+
const environmentId = await resolveEnvironmentId(c);
|
|
1383
|
+
const stored = this.store.read();
|
|
1384
|
+
const runtimeId = stored?.runtimeId;
|
|
1385
|
+
if (!environmentId && !this.cfg.singleEnvironment) {
|
|
1386
|
+
return c.json({ success: false, error: { code: "environment_not_found" } }, 404);
|
|
1387
|
+
}
|
|
1388
|
+
if (!environmentId && !credential()) {
|
|
1389
|
+
return c.json({ success: true, data: { environmentId: null, runtimeId: runtimeId ?? null, bound: false, provider: "objectstack-cloud", connection: null } });
|
|
1390
|
+
}
|
|
1391
|
+
if (cloudUrl) {
|
|
1392
|
+
try {
|
|
1393
|
+
const qs = environmentId ? `?environment_id=${encodeURIComponent(environmentId)}` : runtimeId ? `?runtime_id=${encodeURIComponent(runtimeId)}` : "";
|
|
1394
|
+
const resp = await fetch(`${cloudUrl}/api/v1/cloud-connection/status${qs}`, {
|
|
1395
|
+
headers: authHeaders()
|
|
1396
|
+
});
|
|
1397
|
+
if (resp.ok) {
|
|
1398
|
+
const json = await resp.json().catch(() => null);
|
|
1399
|
+
const data = json?.data ?? {};
|
|
1400
|
+
const bound2 = Boolean(data.bound) || Boolean(credential());
|
|
1401
|
+
return c.json({ success: true, data: {
|
|
1402
|
+
environmentId: environmentId ?? null,
|
|
1403
|
+
runtimeId: data.runtime_id ?? runtimeId ?? null,
|
|
1404
|
+
bound: bound2,
|
|
1405
|
+
provider: "objectstack-cloud",
|
|
1406
|
+
connection: data.connection ?? null
|
|
1407
|
+
} });
|
|
1408
|
+
}
|
|
1409
|
+
} catch {
|
|
1410
|
+
}
|
|
1411
|
+
}
|
|
1412
|
+
const bound = Boolean(credential());
|
|
1413
|
+
return c.json({ success: true, data: { environmentId: environmentId ?? null, runtimeId: runtimeId ?? null, bound, provider: "objectstack-cloud", connection: null } });
|
|
1414
|
+
});
|
|
1415
|
+
rawApp.post(`${CLOUD_CONNECTION_PREFIX}/bind/start`, async (c) => {
|
|
1416
|
+
let body = {};
|
|
1417
|
+
try {
|
|
1418
|
+
body = await c.req.json();
|
|
1419
|
+
} catch {
|
|
1420
|
+
body = {};
|
|
1421
|
+
}
|
|
1422
|
+
let environmentId = await resolveEnvironmentId(c);
|
|
1423
|
+
if (!environmentId && this.cfg.singleEnvironment) {
|
|
1424
|
+
environmentId = String(body?.environment_id ?? body?.environmentId ?? "").trim() || void 0;
|
|
1425
|
+
}
|
|
1426
|
+
if (!environmentId && !this.cfg.singleEnvironment) {
|
|
1427
|
+
return c.json({ success: false, error: { code: "environment_not_found" } }, 404);
|
|
1428
|
+
}
|
|
1429
|
+
const session = await resolveSession(environmentId ?? "", c.req.raw);
|
|
1430
|
+
if (!session?.userId) return c.json({ success: false, error: { code: "unauthenticated", message: "Sign in to this environment to connect a cloud account." } }, 401);
|
|
1431
|
+
if (!cloudUrl) return c.json({ success: false, error: { code: "cloud_unconfigured", message: "No cloud control plane configured." } }, 503);
|
|
1432
|
+
try {
|
|
1433
|
+
const resp = await fetch(`${cloudUrl}/api/v1/auth/device/code`, {
|
|
1434
|
+
method: "POST",
|
|
1435
|
+
headers: { "Content-Type": "application/json" },
|
|
1436
|
+
body: JSON.stringify({ client_id: deviceClientId, scope: deviceScope })
|
|
1437
|
+
});
|
|
1438
|
+
const json = await resp.json().catch(() => ({}));
|
|
1439
|
+
if (!resp.ok) return c.json({ success: false, error: { code: "device_code_failed", message: json?.error ?? `device/code ${resp.status}` } }, 502);
|
|
1440
|
+
const withContext = (uri) => {
|
|
1441
|
+
if (typeof uri !== "string" || !uri) return void 0;
|
|
1442
|
+
try {
|
|
1443
|
+
const u = new URL(uri);
|
|
1444
|
+
try {
|
|
1445
|
+
u.searchParams.set("runtime_name", (0, import_node_os.hostname)());
|
|
1446
|
+
} catch {
|
|
1447
|
+
}
|
|
1448
|
+
const ver = (process.env.OS_RUNTIME_VERSION ?? this.version) || "";
|
|
1449
|
+
if (ver) u.searchParams.set("runtime_version", ver);
|
|
1450
|
+
return u.toString();
|
|
1451
|
+
} catch {
|
|
1452
|
+
return uri;
|
|
1453
|
+
}
|
|
1454
|
+
};
|
|
1455
|
+
return c.json({ success: true, data: {
|
|
1456
|
+
device_code: json.device_code,
|
|
1457
|
+
user_code: json.user_code,
|
|
1458
|
+
verification_uri: withContext(json.verification_uri),
|
|
1459
|
+
verification_uri_complete: withContext(json.verification_uri_complete),
|
|
1460
|
+
interval: json.interval ?? 5,
|
|
1461
|
+
expires_in: json.expires_in ?? 600
|
|
1462
|
+
} });
|
|
1463
|
+
} catch (err) {
|
|
1464
|
+
ctx.logger?.error?.("[CloudConnectionPlugin] bind/start failed", err instanceof Error ? err : new Error(String(err)));
|
|
1465
|
+
return c.json({ success: false, error: { code: "device_code_failed", message: String(err?.message ?? err) } }, 502);
|
|
1466
|
+
}
|
|
1467
|
+
});
|
|
1468
|
+
rawApp.post(`${CLOUD_CONNECTION_PREFIX}/bind/poll`, async (c) => {
|
|
1469
|
+
let body = {};
|
|
1470
|
+
try {
|
|
1471
|
+
body = await c.req.json();
|
|
1472
|
+
} catch {
|
|
1473
|
+
body = {};
|
|
1474
|
+
}
|
|
1475
|
+
let environmentId = await resolveEnvironmentId(c);
|
|
1476
|
+
if (!environmentId && this.cfg.singleEnvironment) {
|
|
1477
|
+
environmentId = String(body?.environment_id ?? body?.environmentId ?? "").trim() || void 0;
|
|
1478
|
+
}
|
|
1479
|
+
if (!environmentId && !this.cfg.singleEnvironment) {
|
|
1480
|
+
return c.json({ success: false, error: { code: "environment_not_found" } }, 404);
|
|
1481
|
+
}
|
|
1482
|
+
const session = await resolveSession(environmentId ?? "", c.req.raw);
|
|
1483
|
+
if (!session?.userId) return c.json({ success: false, error: { code: "unauthenticated" } }, 401);
|
|
1484
|
+
if (!cloudUrl) return c.json({ success: false, error: { code: "cloud_unconfigured" } }, 503);
|
|
1485
|
+
const deviceCode = String(body?.device_code ?? body?.deviceCode ?? "").trim();
|
|
1486
|
+
if (!deviceCode) return c.json({ success: false, error: { code: "invalid_request", message: "device_code is required" } }, 400);
|
|
1487
|
+
try {
|
|
1488
|
+
const tokResp = await fetch(`${cloudUrl}/api/v1/auth/device/token`, {
|
|
1489
|
+
method: "POST",
|
|
1490
|
+
headers: { "Content-Type": "application/json" },
|
|
1491
|
+
body: JSON.stringify({ grant_type: "urn:ietf:params:oauth:grant-type:device_code", device_code: deviceCode, client_id: deviceClientId })
|
|
1492
|
+
});
|
|
1493
|
+
const tok = await tokResp.json().catch(() => ({}));
|
|
1494
|
+
const accessToken = tok?.access_token;
|
|
1495
|
+
if (!accessToken) {
|
|
1496
|
+
const errCode = String(tok?.error ?? `device/token ${tokResp.status}`);
|
|
1497
|
+
const pending = errCode === "authorization_pending" || errCode === "slow_down";
|
|
1498
|
+
return c.json({ success: pending, data: { pending }, error: pending ? void 0 : { code: errCode } }, pending ? 200 : 400);
|
|
1499
|
+
}
|
|
1500
|
+
const stored = this.store.read();
|
|
1501
|
+
const bindResp = await fetch(`${cloudUrl}/api/v1/cloud-connection/bind`, {
|
|
1502
|
+
method: "POST",
|
|
1503
|
+
headers: { "Content-Type": "application/json", ...cloudApiKey ? { Authorization: `Bearer ${cloudApiKey}` } : {} },
|
|
1504
|
+
body: JSON.stringify({
|
|
1505
|
+
...environmentId ? { environment_id: environmentId } : {},
|
|
1506
|
+
...stored?.runtimeId ? { runtime_id: stored.runtimeId } : {},
|
|
1507
|
+
name: (() => {
|
|
1508
|
+
try {
|
|
1509
|
+
return (0, import_node_os.hostname)();
|
|
1510
|
+
} catch {
|
|
1511
|
+
return void 0;
|
|
1512
|
+
}
|
|
1513
|
+
})(),
|
|
1514
|
+
runtime_version: (process.env.OS_RUNTIME_VERSION ?? this.version) || void 0,
|
|
1515
|
+
token: accessToken,
|
|
1516
|
+
scope: deviceScope
|
|
1517
|
+
})
|
|
1518
|
+
});
|
|
1519
|
+
const bindJson = await bindResp.json().catch(() => ({ success: false, error: "bind failed (no body)" }));
|
|
1520
|
+
const runtimeToken = bindJson?.data?.runtime_token;
|
|
1521
|
+
if (bindResp.ok && typeof runtimeToken === "string" && runtimeToken) {
|
|
1522
|
+
try {
|
|
1523
|
+
this.store.write({
|
|
1524
|
+
runtimeToken,
|
|
1525
|
+
runtimeId: bindJson?.data?.runtime_id ?? bindJson?.data?.connection?.runtime_id ?? void 0,
|
|
1526
|
+
environmentId: environmentId || void 0,
|
|
1527
|
+
controlPlaneUrl: cloudUrl,
|
|
1528
|
+
organizationId: bindJson?.data?.connection?.organization_id ?? void 0,
|
|
1529
|
+
accountEmail: bindJson?.data?.connection?.account_email ?? void 0,
|
|
1530
|
+
boundAt: bindJson?.data?.connection?.bound_at ?? (/* @__PURE__ */ new Date()).toISOString()
|
|
1531
|
+
});
|
|
1532
|
+
} catch (err) {
|
|
1533
|
+
ctx.logger?.error?.("[CloudConnectionPlugin] failed to persist runtime credential", err instanceof Error ? err : new Error(String(err)));
|
|
1534
|
+
}
|
|
1535
|
+
delete bindJson.data.runtime_token;
|
|
1536
|
+
}
|
|
1537
|
+
return c.json(bindJson, bindResp.status);
|
|
1538
|
+
} catch (err) {
|
|
1539
|
+
ctx.logger?.error?.("[CloudConnectionPlugin] bind/poll failed", err instanceof Error ? err : new Error(String(err)));
|
|
1540
|
+
return c.json({ success: false, error: { code: "bind_failed", message: String(err?.message ?? err) } }, 502);
|
|
1541
|
+
}
|
|
1542
|
+
});
|
|
1543
|
+
rawApp.post(`${CLOUD_CONNECTION_PREFIX}/unbind`, async (c) => {
|
|
1544
|
+
const environmentId = await resolveEnvironmentId(c);
|
|
1545
|
+
if (!environmentId && !this.cfg.singleEnvironment) {
|
|
1546
|
+
return c.json({ success: false, error: { code: "environment_not_found" } }, 404);
|
|
1547
|
+
}
|
|
1548
|
+
const session = await resolveSession(environmentId ?? "", c.req.raw);
|
|
1549
|
+
if (!session?.userId) return c.json({ success: false, error: { code: "unauthenticated" } }, 401);
|
|
1550
|
+
let revoked = false;
|
|
1551
|
+
if (cloudUrl && credential()) {
|
|
1552
|
+
try {
|
|
1553
|
+
const resp = await fetch(`${cloudUrl}/api/v1/cloud-connection/revoke`, {
|
|
1554
|
+
method: "POST",
|
|
1555
|
+
headers: { "Content-Type": "application/json", ...authHeaders() },
|
|
1556
|
+
body: JSON.stringify(environmentId ? { environment_id: environmentId } : {})
|
|
1557
|
+
});
|
|
1558
|
+
revoked = resp.ok;
|
|
1559
|
+
} catch {
|
|
1560
|
+
}
|
|
1561
|
+
}
|
|
1562
|
+
const residualId = this.store.read()?.runtimeId;
|
|
1563
|
+
const cleared = (() => {
|
|
1564
|
+
try {
|
|
1565
|
+
if (residualId) {
|
|
1566
|
+
this.store.write({ runtimeToken: "", runtimeId: residualId });
|
|
1567
|
+
return true;
|
|
1568
|
+
}
|
|
1569
|
+
return this.store.clear();
|
|
1570
|
+
} catch {
|
|
1571
|
+
return false;
|
|
1572
|
+
}
|
|
1573
|
+
})();
|
|
1574
|
+
return c.json({ success: true, data: { environmentId: environmentId ?? null, revoked, cleared } });
|
|
1575
|
+
});
|
|
1576
|
+
rawApp.post(`${CLOUD_CONNECTION_PREFIX}/install`, async (c) => {
|
|
1577
|
+
const environmentId = await resolveEnvironmentId(c);
|
|
1578
|
+
if (!environmentId) return c.json({ success: false, error: { code: "environment_not_found" } }, 404);
|
|
1579
|
+
const session = await resolveSession(environmentId, c.req.raw);
|
|
1580
|
+
if (!session?.userId) {
|
|
1581
|
+
return c.json({ success: false, error: { code: "unauthenticated", message: "Sign in to this environment to install apps." } }, 401);
|
|
1582
|
+
}
|
|
1583
|
+
if (!cloudUrl || !credential()) {
|
|
1584
|
+
return c.json({ success: false, error: { code: "cloud_unconfigured", message: "This runtime is not connected to a cloud account; install is unavailable." } }, 503);
|
|
1585
|
+
}
|
|
1586
|
+
let body = {};
|
|
1587
|
+
try {
|
|
1588
|
+
body = await c.req.json();
|
|
1589
|
+
} catch {
|
|
1590
|
+
body = {};
|
|
1591
|
+
}
|
|
1592
|
+
const packageId = String(body?.package_id ?? body?.packageId ?? "").trim();
|
|
1593
|
+
if (!packageId) return c.json({ success: false, error: { code: "invalid_request", message: "package_id is required" } }, 400);
|
|
1594
|
+
const seedSampleData = body?.seed_sample_data === true || body?.seedSampleData === true;
|
|
1595
|
+
try {
|
|
1596
|
+
const resp = await fetch(`${cloudUrl}/api/v1/actions/sys_package/install_package`, {
|
|
1597
|
+
method: "POST",
|
|
1598
|
+
headers: {
|
|
1599
|
+
"Content-Type": "application/json",
|
|
1600
|
+
...authHeaders()
|
|
1601
|
+
},
|
|
1602
|
+
body: JSON.stringify({ recordId: packageId, params: { environment_id: environmentId, seed_sample_data: seedSampleData } })
|
|
1603
|
+
});
|
|
1604
|
+
const json = await resp.json().catch(() => ({ success: false, error: "install failed (no body)" }));
|
|
1605
|
+
return c.json(json, resp.status);
|
|
1606
|
+
} catch (err) {
|
|
1607
|
+
ctx.logger?.error?.("[CloudConnectionPlugin] install failed", err instanceof Error ? err : new Error(String(err)));
|
|
1608
|
+
return c.json({ success: false, error: { code: "install_failed", message: String(err?.message ?? err) } }, 502);
|
|
1609
|
+
}
|
|
1610
|
+
});
|
|
1611
|
+
rawApp.get(`${CLOUD_CONNECTION_PREFIX}/installation`, async (c) => {
|
|
1612
|
+
const environmentId = await resolveEnvironmentId(c);
|
|
1613
|
+
if (!environmentId) {
|
|
1614
|
+
if (this.cfg.singleEnvironment) return c.json({ success: true, data: { installed: false } });
|
|
1615
|
+
return c.json({ success: false, error: { code: "environment_not_found" } }, 404);
|
|
1616
|
+
}
|
|
1617
|
+
const session = await resolveSession(environmentId, c.req.raw);
|
|
1618
|
+
if (!session?.userId) {
|
|
1619
|
+
return c.json({ success: false, error: { code: "unauthenticated", message: "Sign in to this environment." } }, 401);
|
|
1620
|
+
}
|
|
1621
|
+
let packageId = "";
|
|
1622
|
+
try {
|
|
1623
|
+
const u = new URL(c.req.url);
|
|
1624
|
+
packageId = String(u.searchParams.get("package_id") ?? u.searchParams.get("packageId") ?? "").trim();
|
|
1625
|
+
} catch {
|
|
1626
|
+
}
|
|
1627
|
+
if (!packageId) return c.json({ success: false, error: { code: "invalid_request", message: "package_id is required" } }, 400);
|
|
1628
|
+
if (!cloudUrl || !credential()) return c.json({ success: true, data: { installed: false } });
|
|
1629
|
+
try {
|
|
1630
|
+
const resp = await fetch(
|
|
1631
|
+
`${cloudUrl}/api/v1/cloud/environments/${encodeURIComponent(environmentId)}/installations/${encodeURIComponent(packageId)}`,
|
|
1632
|
+
{ headers: { Accept: "application/json", ...authHeaders() } }
|
|
1633
|
+
);
|
|
1634
|
+
if (!resp.ok) return c.json({ success: true, data: { installed: false } });
|
|
1635
|
+
const json = await resp.json().catch(() => ({}));
|
|
1636
|
+
const data = json?.data ?? json ?? {};
|
|
1637
|
+
if (!data.installed) return c.json({ success: true, data: { installed: false } });
|
|
1638
|
+
return c.json({ success: true, data: {
|
|
1639
|
+
installed: true,
|
|
1640
|
+
installationId: String(data.installationId ?? ""),
|
|
1641
|
+
version: String(data.version ?? "installed"),
|
|
1642
|
+
withSampleData: data.withSampleData === true
|
|
1643
|
+
} });
|
|
1644
|
+
} catch (err) {
|
|
1645
|
+
ctx.logger?.warn?.(`[CloudConnectionPlugin] installation probe failed: ${String(err?.message ?? err)}`);
|
|
1646
|
+
return c.json({ success: true, data: { installed: false } });
|
|
1647
|
+
}
|
|
1648
|
+
});
|
|
1649
|
+
rawApp.get(`${CLOUD_CONNECTION_PREFIX}/installed`, async (c) => {
|
|
1650
|
+
const environmentId = await resolveEnvironmentId(c);
|
|
1651
|
+
if (!environmentId) {
|
|
1652
|
+
if (this.cfg.singleEnvironment) {
|
|
1653
|
+
return c.json({ success: true, data: { packages: [], total: 0, connected: Boolean(credential()) } });
|
|
1654
|
+
}
|
|
1655
|
+
return c.json({ success: false, error: { code: "environment_not_found" } }, 404);
|
|
1656
|
+
}
|
|
1657
|
+
const session = await resolveSession(environmentId, c.req.raw);
|
|
1658
|
+
if (!session?.userId) {
|
|
1659
|
+
return c.json({ success: false, error: { code: "unauthenticated", message: "Sign in to this environment." } }, 401);
|
|
1660
|
+
}
|
|
1661
|
+
if (!cloudUrl || !credential()) {
|
|
1662
|
+
return c.json({ success: true, data: { packages: [], total: 0, connected: false } });
|
|
1663
|
+
}
|
|
1664
|
+
try {
|
|
1665
|
+
const resp = await fetch(
|
|
1666
|
+
`${cloudUrl}/api/v1/cloud/environments/${encodeURIComponent(environmentId)}/packages`,
|
|
1667
|
+
{ headers: { Accept: "application/json", ...authHeaders() } }
|
|
1668
|
+
);
|
|
1669
|
+
if (!resp.ok) return c.json({ success: true, data: { packages: [], total: 0, connected: true } });
|
|
1670
|
+
const json = await resp.json().catch(() => ({}));
|
|
1671
|
+
const data = json?.data ?? json ?? {};
|
|
1672
|
+
const packages = Array.isArray(data.packages) ? data.packages : [];
|
|
1673
|
+
return c.json({ success: true, data: { packages, total: packages.length, connected: true } });
|
|
1674
|
+
} catch (err) {
|
|
1675
|
+
ctx.logger?.warn?.(`[CloudConnectionPlugin] installed-list failed: ${String(err?.message ?? err)}`);
|
|
1676
|
+
return c.json({ success: true, data: { packages: [], total: 0, connected: true } });
|
|
1677
|
+
}
|
|
1678
|
+
});
|
|
1679
|
+
rawApp.get(`${CLOUD_CONNECTION_PREFIX}/org-packages`, async (c) => {
|
|
1680
|
+
const environmentId = await resolveEnvironmentId(c);
|
|
1681
|
+
if (!environmentId && !this.cfg.singleEnvironment) {
|
|
1682
|
+
return c.json({ success: false, error: { code: "environment_not_found" } }, 404);
|
|
1683
|
+
}
|
|
1684
|
+
const session = await resolveSession(environmentId ?? "", c.req.raw);
|
|
1685
|
+
if (!session?.userId) {
|
|
1686
|
+
return c.json({ success: false, error: { code: "unauthenticated", message: "Sign in to this environment." } }, 401);
|
|
1687
|
+
}
|
|
1688
|
+
if (!cloudUrl || !credential()) {
|
|
1689
|
+
return c.json({ success: true, data: { items: [], total: 0, connected: false } });
|
|
1690
|
+
}
|
|
1691
|
+
try {
|
|
1692
|
+
const qs = environmentId ? `?environment_id=${encodeURIComponent(environmentId)}` : "";
|
|
1693
|
+
const resp = await fetch(
|
|
1694
|
+
`${cloudUrl}/api/v1/cloud/org-packages${qs}`,
|
|
1695
|
+
{ headers: { Accept: "application/json", ...authHeaders() } }
|
|
1696
|
+
);
|
|
1697
|
+
if (!resp.ok) return c.json({ success: true, data: { items: [], total: 0, connected: true } });
|
|
1698
|
+
const json = await resp.json().catch(() => ({}));
|
|
1699
|
+
const data = json?.data ?? json ?? {};
|
|
1700
|
+
const items = Array.isArray(data.items) ? data.items : [];
|
|
1701
|
+
return c.json({ success: true, data: { items, total: items.length, connected: true } });
|
|
1702
|
+
} catch (err) {
|
|
1703
|
+
ctx.logger?.warn?.(`[CloudConnectionPlugin] org-packages failed: ${String(err?.message ?? err)}`);
|
|
1704
|
+
return c.json({ success: true, data: { items: [], total: 0, connected: true } });
|
|
1705
|
+
}
|
|
1706
|
+
});
|
|
1707
|
+
ctx.logger?.info?.(`[CloudConnectionPlugin] mounted ${CLOUD_CONNECTION_PREFIX}/{status,bind/start,bind/poll,install,installation,installed,org-packages} \u2192 ${cloudUrl || "(cloud unconfigured)"}`);
|
|
1708
|
+
});
|
|
1709
|
+
};
|
|
1710
|
+
this.cfg = config;
|
|
1711
|
+
this.store = new ConnectionCredentialStore(config.credentialPath);
|
|
1712
|
+
}
|
|
1713
|
+
};
|
|
1714
|
+
function createCloudConnectionPlugin(config = {}) {
|
|
1715
|
+
return new CloudConnectionPlugin(config);
|
|
1716
|
+
}
|
|
1717
|
+
|
|
1718
|
+
// src/runtime-config-plugin.ts
|
|
1719
|
+
var RuntimeConfigPlugin = class {
|
|
1720
|
+
constructor(config = {}) {
|
|
1721
|
+
this.name = "com.objectstack.runtime.runtime-config";
|
|
1722
|
+
this.version = "1.0.0";
|
|
1723
|
+
this.init = async (_ctx) => {
|
|
1724
|
+
};
|
|
1725
|
+
this.start = async (ctx) => {
|
|
1726
|
+
ctx.hook("kernel:ready", async () => {
|
|
1727
|
+
let httpServer;
|
|
1728
|
+
try {
|
|
1729
|
+
httpServer = ctx.getService("http-server");
|
|
1730
|
+
} catch {
|
|
1731
|
+
ctx.logger?.warn?.("[RuntimeConfigPlugin] http-server not available \u2014 runtime/config not mounted");
|
|
1732
|
+
return;
|
|
1733
|
+
}
|
|
1734
|
+
if (!httpServer || typeof httpServer.getRawApp !== "function") {
|
|
1735
|
+
ctx.logger?.warn?.("[RuntimeConfigPlugin] http-server missing getRawApp() \u2014 runtime/config not mounted");
|
|
1736
|
+
return;
|
|
1737
|
+
}
|
|
1738
|
+
const rawApp = httpServer.getRawApp();
|
|
1739
|
+
let envRegistry = null;
|
|
1740
|
+
try {
|
|
1741
|
+
envRegistry = ctx.getService("env-registry");
|
|
1742
|
+
} catch {
|
|
1743
|
+
}
|
|
1744
|
+
const featuresFor = (plan, base) => {
|
|
1745
|
+
const derived = this.resolvePlanFeatures?.(plan);
|
|
1746
|
+
return {
|
|
1747
|
+
aiStudio: derived?.aiStudio ?? base.aiStudio,
|
|
1748
|
+
autoPublishAiBuilds: derived?.autoPublishAiBuilds ?? base.autoPublishAiBuilds
|
|
1749
|
+
};
|
|
1750
|
+
};
|
|
1751
|
+
const handler = async (c) => {
|
|
1752
|
+
const rawHost = c.req.header("host") ?? "";
|
|
1753
|
+
const host = rawHost.split(":")[0].toLowerCase().trim();
|
|
1754
|
+
let defaultEnvironmentId;
|
|
1755
|
+
let defaultOrgId;
|
|
1756
|
+
let resolvedSingleEnv = this.singleEnvironment;
|
|
1757
|
+
let features = featuresFor(void 0, { aiStudio: this.aiStudio, autoPublishAiBuilds: false });
|
|
1758
|
+
const resolveFn = typeof envRegistry?.resolveByHostname === "function" ? envRegistry.resolveByHostname.bind(envRegistry) : typeof envRegistry?.resolveHostname === "function" ? envRegistry.resolveHostname.bind(envRegistry) : null;
|
|
1759
|
+
if (resolveFn && host) {
|
|
1760
|
+
try {
|
|
1761
|
+
const resolved = await resolveFn(host);
|
|
1762
|
+
if (resolved?.environmentId) {
|
|
1763
|
+
defaultEnvironmentId = String(resolved.environmentId);
|
|
1764
|
+
const orgId = resolved.organizationId ?? resolved.organization_id;
|
|
1765
|
+
if (orgId) defaultOrgId = String(orgId);
|
|
1766
|
+
resolvedSingleEnv = true;
|
|
1767
|
+
if (typeof resolved.plan === "string" && resolved.plan.trim() !== "") {
|
|
1768
|
+
features = featuresFor(resolved.plan, features);
|
|
1769
|
+
}
|
|
1770
|
+
}
|
|
1771
|
+
} catch {
|
|
1772
|
+
}
|
|
1773
|
+
}
|
|
1774
|
+
return c.json({
|
|
1775
|
+
cloudUrl: this.cloudUrl,
|
|
1776
|
+
singleEnvironment: resolvedSingleEnv,
|
|
1777
|
+
defaultOrgId,
|
|
1778
|
+
defaultEnvironmentId,
|
|
1779
|
+
features: {
|
|
1780
|
+
installLocal: this.installLocal,
|
|
1781
|
+
marketplace: true,
|
|
1782
|
+
aiStudio: features.aiStudio,
|
|
1783
|
+
autoPublishAiBuilds: features.autoPublishAiBuilds
|
|
1784
|
+
},
|
|
1785
|
+
branding: {
|
|
1786
|
+
productName: this.productName,
|
|
1787
|
+
productShortName: this.productShortName
|
|
1788
|
+
}
|
|
1789
|
+
});
|
|
1790
|
+
};
|
|
1791
|
+
rawApp.get("/api/v1/runtime/config", handler);
|
|
1792
|
+
rawApp.get("/api/v1/studio/runtime-config", handler);
|
|
1793
|
+
ctx.logger?.info?.("[RuntimeConfigPlugin] mounted /api/v1/runtime/config", {
|
|
1794
|
+
cloudUrl: this.cloudUrl || "(empty)",
|
|
1795
|
+
installLocal: this.installLocal,
|
|
1796
|
+
perHostEnvResolution: !!envRegistry
|
|
1797
|
+
});
|
|
1798
|
+
});
|
|
1799
|
+
};
|
|
1800
|
+
this.destroy = async () => {
|
|
1801
|
+
};
|
|
1802
|
+
this.cloudUrl = config.controlPlaneUrl === "" ? "" : resolveCloudUrl(config.controlPlaneUrl) ?? "";
|
|
1803
|
+
this.installLocal = !!config.installLocal;
|
|
1804
|
+
this.aiStudio = config.aiStudio !== false;
|
|
1805
|
+
this.singleEnvironment = !!config.singleEnvironment;
|
|
1806
|
+
this.resolvePlanFeatures = config.resolvePlanFeatures;
|
|
1807
|
+
const envName = (typeof process !== "undefined" ? process.env?.OS_PRODUCT_NAME : void 0)?.trim();
|
|
1808
|
+
const envShort = (typeof process !== "undefined" ? process.env?.OS_PRODUCT_SHORT_NAME : void 0)?.trim();
|
|
1809
|
+
this.productName = (config.productName ?? envName ?? "ObjectOS").trim() || "ObjectOS";
|
|
1810
|
+
this.productShortName = (config.productShortName ?? envShort ?? this.productName).trim() || this.productName;
|
|
1811
|
+
}
|
|
1812
|
+
};
|
|
1813
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
1814
|
+
0 && (module.exports = {
|
|
1815
|
+
CLOUD_CONNECTION_UI_BUNDLE,
|
|
1816
|
+
CloudConnectionPlugin,
|
|
1817
|
+
CloudConnectionSettingsPage,
|
|
1818
|
+
ConnectionCredentialStore,
|
|
1819
|
+
DEFAULT_CLOUD_URL,
|
|
1820
|
+
DEFAULT_CONNECTION_CREDENTIAL_PATH,
|
|
1821
|
+
DEFAULT_INSTALLED_PACKAGES_DIR,
|
|
1822
|
+
LocalManifestSource,
|
|
1823
|
+
MARKETPLACE_BROWSE_UI_BUNDLE,
|
|
1824
|
+
MARKETPLACE_INSTALLED_UI_BUNDLE,
|
|
1825
|
+
MarketplaceInstallLocalPlugin,
|
|
1826
|
+
MarketplaceProxyPlugin,
|
|
1827
|
+
RuntimeConfigPlugin,
|
|
1828
|
+
createCloudConnectionPlugin,
|
|
1829
|
+
publicMarketplaceKeyForApiPath,
|
|
1830
|
+
resolveCloudUrl,
|
|
1831
|
+
resolveMarketplacePublicBaseUrl
|
|
1832
|
+
});
|
|
1833
|
+
//# sourceMappingURL=index.cjs.map
|