playcanvas-agent-bridge-cli 0.2.1 → 0.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.
@@ -0,0 +1,369 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { mkdir, readFile, readdir, rename, rm, stat, writeFile, } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ import { t as inspectTar, x as extractTar } from "tar";
5
+ import { CONFIG_DIR, DEFAULT_FRONTEND_REPOSITORY, VERSION, } from "../config.js";
6
+ const RELEASE_PATTERN = /^playcanvas-editor-v\d+\.\d+\.\d+-r\d+$/;
7
+ const SHA256_PATTERN = /^[a-f0-9]{64}$/;
8
+ const COMMIT_PATTERN = /^[a-f0-9]{40}$/;
9
+ const MAX_ARCHIVE_SIZE = 250 * 1024 * 1024;
10
+ const MAX_EXTRACTED_SIZE = 1024 * 1024 * 1024;
11
+ const MAX_ARCHIVE_ENTRIES = 100_000;
12
+ const REQUIRED_FILES = [
13
+ "dist/js/editor.js",
14
+ "dist/js/editor-empty.js",
15
+ "dist/js/code-editor.js",
16
+ "dist/js/launch.js",
17
+ "dist/css/editor.css",
18
+ "dist/css/code-editor.css",
19
+ "dist/css/launch.css",
20
+ ];
21
+ export class FrontendError extends Error {
22
+ code;
23
+ constructor(code, message) {
24
+ super(message);
25
+ this.name = "FrontendError";
26
+ this.code = code;
27
+ }
28
+ }
29
+ function storePaths(rootDir = CONFIG_DIR) {
30
+ const frontendsDir = join(rootDir, "frontends");
31
+ return {
32
+ rootDir,
33
+ frontendsDir,
34
+ stateFile: join(rootDir, "frontend-state.json"),
35
+ };
36
+ }
37
+ function isObject(value) {
38
+ return Boolean(value && typeof value === "object" && !Array.isArray(value));
39
+ }
40
+ function assertReleaseName(release) {
41
+ if (!RELEASE_PATTERN.test(release)) {
42
+ throw new FrontendError("INVALID_FRONTEND_RELEASE", `Invalid frontend release name: ${release}`);
43
+ }
44
+ }
45
+ function parseVersion(version) {
46
+ const match = /^(\d+)\.(\d+)\.(\d+)$/.exec(version);
47
+ if (!match) {
48
+ throw new FrontendError("INVALID_FRONTEND_MANIFEST", `Invalid version: ${version}`);
49
+ }
50
+ return [Number(match[1]), Number(match[2]), Number(match[3])];
51
+ }
52
+ function compareVersions(left, right) {
53
+ const a = parseVersion(left);
54
+ const b = parseVersion(right);
55
+ for (let index = 0; index < a.length; index += 1) {
56
+ if (a[index] !== b[index])
57
+ return a[index] - b[index];
58
+ }
59
+ return 0;
60
+ }
61
+ export function validateFrontendManifest(value) {
62
+ if (!isObject(value) || value.schemaVersion !== 1) {
63
+ throw new FrontendError("INVALID_FRONTEND_MANIFEST", "Unsupported frontend manifest.");
64
+ }
65
+ const archive = value.archive;
66
+ if (!isObject(archive)) {
67
+ throw new FrontendError("INVALID_FRONTEND_MANIFEST", "Frontend archive metadata is missing.");
68
+ }
69
+ const manifest = value;
70
+ assertReleaseName(manifest.release);
71
+ if (typeof manifest.editorVersion !== "string" ||
72
+ typeof manifest.sourceRepository !== "string" ||
73
+ typeof manifest.sourceCommit !== "string" ||
74
+ typeof manifest.builtAt !== "string" ||
75
+ typeof manifest.minPcbridgeVersion !== "string" ||
76
+ typeof manifest.archive.name !== "string" ||
77
+ typeof manifest.archive.url !== "string" ||
78
+ typeof manifest.archive.sha256 !== "string" ||
79
+ typeof manifest.archive.size !== "number") {
80
+ throw new FrontendError("INVALID_FRONTEND_MANIFEST", "Frontend manifest fields are invalid.");
81
+ }
82
+ parseVersion(manifest.editorVersion);
83
+ parseVersion(manifest.minPcbridgeVersion);
84
+ if (!manifest.release.startsWith(`playcanvas-editor-v${manifest.editorVersion}-r`)) {
85
+ throw new FrontendError("INVALID_FRONTEND_MANIFEST", "Frontend release name does not match the Editor version.");
86
+ }
87
+ if (Number.isNaN(Date.parse(manifest.builtAt))) {
88
+ throw new FrontendError("INVALID_FRONTEND_MANIFEST", "Frontend build time is invalid.");
89
+ }
90
+ if (manifest.sourceRepository !== DEFAULT_FRONTEND_REPOSITORY) {
91
+ throw new FrontendError("UNTRUSTED_FRONTEND_SOURCE", `Unexpected frontend repository: ${manifest.sourceRepository}`);
92
+ }
93
+ if (!COMMIT_PATTERN.test(manifest.sourceCommit)) {
94
+ throw new FrontendError("INVALID_FRONTEND_MANIFEST", "Frontend source commit is invalid.");
95
+ }
96
+ if (manifest.archive.name !== `${manifest.release}.tar.gz`) {
97
+ throw new FrontendError("INVALID_FRONTEND_MANIFEST", "Frontend archive name is invalid.");
98
+ }
99
+ if (!SHA256_PATTERN.test(manifest.archive.sha256)) {
100
+ throw new FrontendError("INVALID_FRONTEND_MANIFEST", "Frontend archive SHA-256 is invalid.");
101
+ }
102
+ if (!Number.isSafeInteger(manifest.archive.size) ||
103
+ manifest.archive.size <= 0 ||
104
+ manifest.archive.size > MAX_ARCHIVE_SIZE) {
105
+ throw new FrontendError("INVALID_FRONTEND_MANIFEST", "Frontend archive size is invalid.");
106
+ }
107
+ let archiveUrl;
108
+ try {
109
+ archiveUrl = new URL(manifest.archive.url);
110
+ }
111
+ catch {
112
+ throw new FrontendError("INVALID_FRONTEND_MANIFEST", "Frontend archive URL is invalid.");
113
+ }
114
+ const expectedPath = `/${DEFAULT_FRONTEND_REPOSITORY}/releases/download/` +
115
+ `${manifest.release}/${manifest.archive.name}`;
116
+ if (archiveUrl.protocol !== "https:" ||
117
+ archiveUrl.hostname !== "github.com" ||
118
+ archiveUrl.pathname !== expectedPath ||
119
+ archiveUrl.search ||
120
+ archiveUrl.hash) {
121
+ throw new FrontendError("UNTRUSTED_FRONTEND_SOURCE", "Frontend archive URL is not trusted.");
122
+ }
123
+ if (compareVersions(VERSION, manifest.minPcbridgeVersion) < 0) {
124
+ throw new FrontendError("FRONTEND_REQUIRES_NEWER_CLI", `Frontend ${manifest.release} requires pcbridge ${manifest.minPcbridgeVersion} or newer.`);
125
+ }
126
+ return manifest;
127
+ }
128
+ export function frontendManifestUrl(release = "latest") {
129
+ if (release === "latest") {
130
+ return `https://github.com/${DEFAULT_FRONTEND_REPOSITORY}/releases/latest/download/release.json`;
131
+ }
132
+ assertReleaseName(release);
133
+ return (`https://github.com/${DEFAULT_FRONTEND_REPOSITORY}/releases/download/` +
134
+ `${release}/release.json`);
135
+ }
136
+ export async function fetchFrontendManifest(release = "latest", options = {}) {
137
+ const fetchImpl = options.fetch || fetch;
138
+ let response;
139
+ try {
140
+ response = await fetchImpl(frontendManifestUrl(release), {
141
+ headers: {
142
+ Accept: "application/json",
143
+ "User-Agent": `playcanvas-agent-bridge-cli/${VERSION}`,
144
+ },
145
+ redirect: "follow",
146
+ });
147
+ }
148
+ catch (error) {
149
+ throw new FrontendError("FRONTEND_MANIFEST_DOWNLOAD_FAILED", `Cannot download frontend manifest: ${String(error)}`);
150
+ }
151
+ if (!response.ok) {
152
+ throw new FrontendError("FRONTEND_MANIFEST_DOWNLOAD_FAILED", `Cannot download frontend manifest: HTTP ${response.status}.`);
153
+ }
154
+ try {
155
+ return validateFrontendManifest(await response.json());
156
+ }
157
+ catch (error) {
158
+ if (error instanceof FrontendError)
159
+ throw error;
160
+ throw new FrontendError("INVALID_FRONTEND_MANIFEST", "Frontend manifest is not valid JSON.");
161
+ }
162
+ }
163
+ async function readState(rootDir = CONFIG_DIR) {
164
+ const { stateFile } = storePaths(rootDir);
165
+ try {
166
+ const value = JSON.parse(await readFile(stateFile, "utf8"));
167
+ if (isObject(value) &&
168
+ (value.activeRelease === null || typeof value.activeRelease === "string") &&
169
+ typeof value.updatedAt === "string") {
170
+ if (typeof value.activeRelease === "string")
171
+ assertReleaseName(value.activeRelease);
172
+ return value;
173
+ }
174
+ }
175
+ catch {
176
+ // Missing or invalid state falls back to no active frontend.
177
+ }
178
+ return { activeRelease: null, updatedAt: "" };
179
+ }
180
+ async function writeState(state, rootDir = CONFIG_DIR) {
181
+ const { stateFile } = storePaths(rootDir);
182
+ await mkdir(rootDir, { recursive: true });
183
+ const temporary = `${stateFile}.${process.pid}.${randomUUID()}.tmp`;
184
+ await writeFile(temporary, `${JSON.stringify(state, null, 2)}\n`, { mode: 0o600 });
185
+ await rename(temporary, stateFile);
186
+ }
187
+ async function validateInstalledFrontend(directory) {
188
+ for (const file of REQUIRED_FILES) {
189
+ const info = await stat(join(directory, file)).catch(() => null);
190
+ if (!info?.isFile()) {
191
+ throw new FrontendError("INVALID_FRONTEND_ARCHIVE", `Frontend archive is missing ${file}.`);
192
+ }
193
+ }
194
+ const monaco = await stat(join(directory, "dist/js/monaco-editor")).catch(() => null);
195
+ const wasm = await stat(join(directory, "dist/wasm")).catch(() => null);
196
+ if (!monaco?.isDirectory() || !wasm?.isDirectory()) {
197
+ throw new FrontendError("INVALID_FRONTEND_ARCHIVE", "Frontend archive is missing Monaco or WASM assets.");
198
+ }
199
+ }
200
+ function validateArchiveEntry(path, type) {
201
+ const normalized = path.replaceAll("\\", "/");
202
+ if (!normalized ||
203
+ normalized.startsWith("/") ||
204
+ normalized.split("/").some((part) => part === "..")) {
205
+ throw new FrontendError("INVALID_FRONTEND_ARCHIVE", `Unsafe frontend archive path: ${path}`);
206
+ }
207
+ if (normalized !== "LICENSE" &&
208
+ normalized !== "dist" &&
209
+ normalized !== "dist/" &&
210
+ !normalized.startsWith("dist/")) {
211
+ throw new FrontendError("INVALID_FRONTEND_ARCHIVE", `Unexpected frontend archive path: ${path}`);
212
+ }
213
+ if (!["File", "OldFile", "Directory"].includes(type)) {
214
+ throw new FrontendError("INVALID_FRONTEND_ARCHIVE", `Unsupported frontend archive entry type: ${type}`);
215
+ }
216
+ }
217
+ async function installedManifest(directory) {
218
+ try {
219
+ const manifest = validateFrontendManifest(JSON.parse(await readFile(join(directory, "release.json"), "utf8")));
220
+ await validateInstalledFrontend(directory);
221
+ return manifest;
222
+ }
223
+ catch {
224
+ return null;
225
+ }
226
+ }
227
+ export async function installFrontend(release = "latest", options = {}) {
228
+ const rootDir = options.rootDir || CONFIG_DIR;
229
+ const fetchImpl = options.fetch || fetch;
230
+ const { frontendsDir } = storePaths(rootDir);
231
+ const manifest = await fetchFrontendManifest(release, { fetch: fetchImpl });
232
+ const targetDir = join(frontendsDir, manifest.release);
233
+ const existing = await installedManifest(targetDir);
234
+ if (existing?.archive.sha256 === manifest.archive.sha256) {
235
+ if (options.activate !== false) {
236
+ await useFrontend(manifest.release, { rootDir });
237
+ }
238
+ return { manifest: existing, path: targetDir, alreadyInstalled: true };
239
+ }
240
+ await mkdir(frontendsDir, { recursive: true });
241
+ const installId = `${manifest.release}.${process.pid}.${randomUUID()}`;
242
+ const archiveFile = join(frontendsDir, `.${installId}.tar.gz.part`);
243
+ const extractDir = join(frontendsDir, `.${installId}.extract`);
244
+ try {
245
+ let response;
246
+ try {
247
+ response = await fetchImpl(manifest.archive.url, {
248
+ headers: {
249
+ Accept: "application/gzip, application/octet-stream",
250
+ "User-Agent": `playcanvas-agent-bridge-cli/${VERSION}`,
251
+ },
252
+ redirect: "follow",
253
+ });
254
+ }
255
+ catch (error) {
256
+ throw new FrontendError("FRONTEND_DOWNLOAD_FAILED", `Cannot download frontend archive: ${String(error)}`);
257
+ }
258
+ if (!response.ok) {
259
+ throw new FrontendError("FRONTEND_DOWNLOAD_FAILED", `Cannot download frontend archive: HTTP ${response.status}.`);
260
+ }
261
+ const archive = Buffer.from(await response.arrayBuffer());
262
+ if (archive.length !== manifest.archive.size) {
263
+ throw new FrontendError("FRONTEND_SIZE_MISMATCH", `Frontend archive size mismatch: expected ${manifest.archive.size}, got ${archive.length}.`);
264
+ }
265
+ const digest = createHash("sha256").update(archive).digest("hex");
266
+ if (digest !== manifest.archive.sha256) {
267
+ throw new FrontendError("FRONTEND_CHECKSUM_MISMATCH", "Frontend archive SHA-256 verification failed.");
268
+ }
269
+ await writeFile(archiveFile, archive, { mode: 0o600 });
270
+ await mkdir(extractDir, { recursive: true });
271
+ let entryCount = 0;
272
+ let extractedSize = 0;
273
+ await inspectTar({
274
+ file: archiveFile,
275
+ onentry: (entry) => {
276
+ validateArchiveEntry(entry.path, entry.type);
277
+ entryCount += 1;
278
+ extractedSize += entry.size;
279
+ if (entryCount > MAX_ARCHIVE_ENTRIES ||
280
+ extractedSize > MAX_EXTRACTED_SIZE) {
281
+ throw new FrontendError("INVALID_FRONTEND_ARCHIVE", "Frontend archive expands beyond the safety limit.");
282
+ }
283
+ },
284
+ });
285
+ await extractTar({
286
+ cwd: extractDir,
287
+ file: archiveFile,
288
+ preservePaths: false,
289
+ strict: true,
290
+ });
291
+ await validateInstalledFrontend(extractDir);
292
+ await writeFile(join(extractDir, "release.json"), `${JSON.stringify(manifest, null, 2)}\n`, { mode: 0o600 });
293
+ await rm(targetDir, { force: true, recursive: true });
294
+ await rename(extractDir, targetDir);
295
+ if (options.activate !== false) {
296
+ await useFrontend(manifest.release, { rootDir });
297
+ }
298
+ return { manifest, path: targetDir, alreadyInstalled: false };
299
+ }
300
+ finally {
301
+ await rm(archiveFile, { force: true });
302
+ await rm(extractDir, { force: true, recursive: true });
303
+ }
304
+ }
305
+ export async function listFrontends(options = {}) {
306
+ const rootDir = options.rootDir || CONFIG_DIR;
307
+ const { frontendsDir } = storePaths(rootDir);
308
+ const state = await readState(rootDir);
309
+ const entries = await readdir(frontendsDir, { withFileTypes: true }).catch(() => []);
310
+ const installed = [];
311
+ for (const entry of entries) {
312
+ if (!entry.isDirectory() || entry.name.startsWith("."))
313
+ continue;
314
+ const path = join(frontendsDir, entry.name);
315
+ const manifest = await installedManifest(path);
316
+ if (!manifest)
317
+ continue;
318
+ installed.push({
319
+ release: manifest.release,
320
+ editorVersion: manifest.editorVersion,
321
+ sourceCommit: manifest.sourceCommit,
322
+ builtAt: manifest.builtAt,
323
+ path,
324
+ active: state.activeRelease === manifest.release,
325
+ });
326
+ }
327
+ return installed.sort((left, right) => right.release.localeCompare(left.release));
328
+ }
329
+ export async function getFrontendStatus(options = {}) {
330
+ const rootDir = options.rootDir || CONFIG_DIR;
331
+ const state = await readState(rootDir);
332
+ const installed = await listFrontends({ rootDir });
333
+ const active = installed.find((item) => item.release === state.activeRelease) || null;
334
+ return {
335
+ ready: Boolean(active),
336
+ activeRelease: active?.release || null,
337
+ activePath: active ? join(active.path, "dist") : null,
338
+ installed,
339
+ };
340
+ }
341
+ export async function useFrontend(release, options = {}) {
342
+ assertReleaseName(release);
343
+ const rootDir = options.rootDir || CONFIG_DIR;
344
+ const { frontendsDir } = storePaths(rootDir);
345
+ const directory = join(frontendsDir, release);
346
+ if (!(await installedManifest(directory))) {
347
+ throw new FrontendError("FRONTEND_NOT_INSTALLED", `Frontend ${release} is not installed.`);
348
+ }
349
+ await writeState({
350
+ activeRelease: release,
351
+ updatedAt: new Date().toISOString(),
352
+ }, rootDir);
353
+ return getFrontendStatus({ rootDir });
354
+ }
355
+ export async function removeFrontend(release, options = {}) {
356
+ assertReleaseName(release);
357
+ const rootDir = options.rootDir || CONFIG_DIR;
358
+ const { frontendsDir } = storePaths(rootDir);
359
+ const state = await readState(rootDir);
360
+ if (state.activeRelease === release) {
361
+ throw new FrontendError("FRONTEND_IS_ACTIVE", `Frontend ${release} is active. Select another version before removing it.`);
362
+ }
363
+ const directory = join(frontendsDir, release);
364
+ if (!(await installedManifest(directory))) {
365
+ throw new FrontendError("FRONTEND_NOT_INSTALLED", `Frontend ${release} is not installed.`);
366
+ }
367
+ await rm(directory, { force: true, recursive: true });
368
+ return getFrontendStatus({ rootDir });
369
+ }