castle-web-cli 0.4.148 → 0.4.150
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api.d.ts +14 -0
- package/dist/api.js +18 -0
- package/dist/castle-host/host.d.ts +17 -0
- package/dist/castle-host/host.js +58 -0
- package/dist/castleJson.d.ts +15 -0
- package/dist/castleJson.js +36 -0
- package/dist/devSessionChild.d.ts +1 -0
- package/dist/devSessionChild.js +129 -0
- package/dist/devSessionServer.d.ts +19 -0
- package/dist/devSessionServer.js +511 -0
- package/dist/index.js +8 -8
- package/dist/init.js +10 -2
- package/dist/list-decks.js +7 -6
- package/dist/preview.d.ts +1 -1
- package/dist/preview.js +4 -2
- package/dist/save-deck.js +63 -14
- package/dist/serve.js +269 -108
- package/dist/serveSecurity.d.ts +7 -1
- package/dist/serveSecurity.js +65 -16
- package/dist/serverBundle.d.ts +8 -0
- package/dist/serverBundle.js +82 -0
- package/dist/shell/assets/{index-CL9TuLXb.js → index-Dlhc3eZW.js} +42 -42
- package/dist/shell/assets/index-DwezawBs.css +1 -0
- package/dist/shell/index.html +2 -2
- package/kits/blank/castle.json +5 -2
- package/kits/physics-2d/behaviors/Collider.jsx +1 -2
- package/kits/physics-2d/behaviors/Joints.jsx +1 -1
- package/kits/physics-2d/castle.json +1 -1
- package/kits/physics-2d/editors/BlueprintLibrary.jsx +33 -3
- package/kits/physics-2d/editors/SceneEditor.jsx +319 -140
- package/kits/physics-2d/editors/SingleEditor.jsx +6 -0
- package/kits/physics-2d/engine/blueprint.js +106 -14
- package/kits/physics-2d/engine/scene.js +9 -2
- package/kits/physics-2d/engine/ui.jsx +30 -2
- package/kits/physics-2d/engine/ui.module.css +59 -0
- package/kits/physics-3d/castle.json +1 -1
- package/kits/physics-3d/engine3d/PxModelEditor.jsx +29 -13
- package/kits/physics-3d/engine3d/Scene3DEditor.jsx +26 -7
- package/kits/physics-3d/engine3d/editorChrome.jsx +26 -1
- package/package.json +1 -1
- package/dist/shell/assets/index-DN8HQBnW.css +0 -1
package/dist/serve.js
CHANGED
|
@@ -17,8 +17,10 @@ import { FORKS_DIR, ownForkFile, splitImportRel } from './forks.js';
|
|
|
17
17
|
import * as config from './config.js';
|
|
18
18
|
import { graphql as castleGraphql } from './api.js';
|
|
19
19
|
import { executeCommand } from './castle-host/host.js';
|
|
20
|
-
import { ServeSecurity
|
|
20
|
+
import { ServeSecurity } from './serveSecurity.js';
|
|
21
21
|
import { isSameOriginUpgrade } from './wsOrigin.js';
|
|
22
|
+
import { resolveServerConfig } from './castleJson.js';
|
|
23
|
+
import { startDevSessionServer, } from './devSessionServer.js';
|
|
22
24
|
// The log is a tail, not an archive: append, and once it passes the cap drop
|
|
23
25
|
// whole lines off the front until it is back under.
|
|
24
26
|
const LOG_MAX_BYTES = 2 * 1024 * 1024;
|
|
@@ -46,25 +48,14 @@ function isPortFree(port) {
|
|
|
46
48
|
});
|
|
47
49
|
});
|
|
48
50
|
}
|
|
49
|
-
async function
|
|
50
|
-
for (let
|
|
51
|
-
if (
|
|
52
|
-
return
|
|
53
|
-
}
|
|
54
|
-
}
|
|
55
|
-
throw new Error(`No free port pair found starting from ${startPort}`);
|
|
56
|
-
}
|
|
57
|
-
async function findLocalContentPorts(startPort, reserved) {
|
|
58
|
-
const free = [];
|
|
59
|
-
for (let port = startPort; port < startPort + 100 && free.length < 2; port++) {
|
|
60
|
-
if (!reserved.has(port) && (await isPortFree(port)))
|
|
61
|
-
free.push(port);
|
|
51
|
+
async function findFreePort(startPort) {
|
|
52
|
+
for (let port = startPort; port < startPort + 100; port += 1) {
|
|
53
|
+
if (await isPortFree(port))
|
|
54
|
+
return port;
|
|
62
55
|
}
|
|
63
|
-
|
|
64
|
-
throw new Error(`No free local content ports found from ${startPort}`);
|
|
65
|
-
return { edit: free[0], play: free[1] };
|
|
56
|
+
throw new Error(`No free port found starting from ${startPort}`);
|
|
66
57
|
}
|
|
67
|
-
function listenLocalContentServer(upstreamHost, upstreamPort,
|
|
58
|
+
function listenLocalContentServer(upstreamHost, upstreamPort, role, security, reserved) {
|
|
68
59
|
const upstreamHeaders = (req) => ({
|
|
69
60
|
...req.headers,
|
|
70
61
|
...security.localContentProxyHeaders(role),
|
|
@@ -89,7 +80,12 @@ function listenLocalContentServer(upstreamHost, upstreamPort, port, role, securi
|
|
|
89
80
|
req.pipe(upstream);
|
|
90
81
|
});
|
|
91
82
|
server.on('upgrade', (req, socket, head) => {
|
|
92
|
-
|
|
83
|
+
const multiplayer = isDevMultiplayerUpgrade(req);
|
|
84
|
+
if (!isViteClientUpgrade(req) && !multiplayer) {
|
|
85
|
+
socket.destroy();
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
if (multiplayer && !isSameOriginUpgrade(req)) {
|
|
93
89
|
socket.destroy();
|
|
94
90
|
return;
|
|
95
91
|
}
|
|
@@ -97,9 +93,26 @@ function listenLocalContentServer(upstreamHost, upstreamPort, port, role, securi
|
|
|
97
93
|
});
|
|
98
94
|
return new Promise((resolve, reject) => {
|
|
99
95
|
server.once('error', reject);
|
|
100
|
-
|
|
96
|
+
// These listeners exist only to give local Safari two distinct loopback
|
|
97
|
+
// origins. Let the OS allocate them atomically; their numbers are not part
|
|
98
|
+
// of the cloud serve contract and must never occupy a future deck port by
|
|
99
|
+
// convention. Retry the vanishingly rare case where port 0 selects the
|
|
100
|
+
// main Vite port before Vite itself has bound it.
|
|
101
|
+
server.listen(0, '127.0.0.1', () => {
|
|
101
102
|
server.off('error', reject);
|
|
102
|
-
|
|
103
|
+
const address = server.address();
|
|
104
|
+
const port = typeof address === 'object' && address ? address.port : 0;
|
|
105
|
+
if (!port) {
|
|
106
|
+
server.close(() => reject(new Error('local content proxy has no listening port')));
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
if (reserved.has(port)) {
|
|
110
|
+
server.close(() => {
|
|
111
|
+
void listenLocalContentServer(upstreamHost, upstreamPort, role, security, reserved).then(resolve, reject);
|
|
112
|
+
});
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
resolve({ server, port });
|
|
103
116
|
});
|
|
104
117
|
});
|
|
105
118
|
}
|
|
@@ -141,15 +154,25 @@ export function isViteClientUpgrade(req) {
|
|
|
141
154
|
return false;
|
|
142
155
|
}
|
|
143
156
|
}
|
|
144
|
-
|
|
157
|
+
function isDevMultiplayerUpgrade(req) {
|
|
158
|
+
try {
|
|
159
|
+
return new URL(req.url || '/', 'http://localhost').pathname === '/__castle/mp';
|
|
160
|
+
}
|
|
161
|
+
catch {
|
|
162
|
+
return false;
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
async function startLocalContentServers(upstreamHost, upstreamPort, security, reserved) {
|
|
145
166
|
const servers = [];
|
|
167
|
+
const ports = {};
|
|
146
168
|
try {
|
|
147
|
-
for (const [
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
169
|
+
for (const role of ['edit', 'play']) {
|
|
170
|
+
const listening = await listenLocalContentServer(upstreamHost, upstreamPort, role, security, reserved);
|
|
171
|
+
servers.push(listening.server);
|
|
172
|
+
ports[role] = listening.port;
|
|
173
|
+
reserved.add(listening.port);
|
|
152
174
|
}
|
|
175
|
+
security.setLocalContentPorts(ports);
|
|
153
176
|
return servers;
|
|
154
177
|
}
|
|
155
178
|
catch (error) {
|
|
@@ -205,7 +228,7 @@ export function isAllowedShellHost(hostHeader, configuredHost) {
|
|
|
205
228
|
if (host.endsWith('.local') || host.endsWith('.ts.net'))
|
|
206
229
|
return true;
|
|
207
230
|
const configured = configuredHost ? hostnameFromHeader(configuredHost) : '';
|
|
208
|
-
return configured !== '' && configured !== '0.0.0.0' && configured !== '::' && host === configured;
|
|
231
|
+
return (configured !== '' && configured !== '0.0.0.0' && configured !== '::' && host === configured);
|
|
209
232
|
}
|
|
210
233
|
const EDIT_CONTENT_READ_ENDPOINTS = new Set([
|
|
211
234
|
'/__castle/files/raw',
|
|
@@ -243,6 +266,21 @@ window.__castleShellOrigin=(function(){
|
|
|
243
266
|
if(h.endsWith('.sandboxes.castlexyz.com'))return 'https://'+p+'-'+sid+'.sandboxes.castle.xyz';
|
|
244
267
|
return null;
|
|
245
268
|
})();
|
|
269
|
+
(function(){
|
|
270
|
+
var role=new URLSearchParams(location.search).get('edit')==='0'?'play':'edit';
|
|
271
|
+
var target=window.__castleShellOrigin||'*';
|
|
272
|
+
var announce=function(){
|
|
273
|
+
if(window.parent===window)return;
|
|
274
|
+
window.parent.postMessage({type:'castle-content-frame-ready',role:role},target);
|
|
275
|
+
};
|
|
276
|
+
window.addEventListener('message',function(event){
|
|
277
|
+
var d=event&&event.data;
|
|
278
|
+
if(event.source!==window.parent||!d||d.type!=='castle-request-content-frame-ready')return;
|
|
279
|
+
if(window.__castleShellOrigin&&event.origin!==window.__castleShellOrigin)return;
|
|
280
|
+
announce();
|
|
281
|
+
});
|
|
282
|
+
window.addEventListener('load',function(){setTimeout(announce,0);},{once:true});
|
|
283
|
+
})();
|
|
246
284
|
</script>\n ${CONSOLE_CAPTURE}`);
|
|
247
285
|
},
|
|
248
286
|
},
|
|
@@ -262,10 +300,14 @@ window.__castleShellOrigin=(function(){
|
|
|
262
300
|
return;
|
|
263
301
|
}
|
|
264
302
|
if (reqPath === '/__castle/ws-ticket') {
|
|
265
|
-
if (content || req.method !== 'POST'
|
|
303
|
+
if (content || req.method !== 'POST') {
|
|
266
304
|
res.writeHead(403).end();
|
|
267
305
|
return;
|
|
268
306
|
}
|
|
307
|
+
if (!security.authorizeHttp(req)) {
|
|
308
|
+
security.rejectHttpAuth(res);
|
|
309
|
+
return;
|
|
310
|
+
}
|
|
269
311
|
const endpoint = new URL(req.url || '/', 'http://localhost').searchParams.get('endpoint');
|
|
270
312
|
if (endpoint !== 'serve' && endpoint !== 'pty' && endpoint !== 'agent') {
|
|
271
313
|
res.writeHead(400).end('invalid endpoint');
|
|
@@ -275,7 +317,9 @@ window.__castleShellOrigin=(function(){
|
|
|
275
317
|
res.end(JSON.stringify({ ticket: security.issueTicket(endpoint) }));
|
|
276
318
|
return;
|
|
277
319
|
}
|
|
278
|
-
if (reqPath === '/__castle/auth' ||
|
|
320
|
+
if (reqPath === '/__castle/auth' ||
|
|
321
|
+
reqPath === '/__castle/ws-port' ||
|
|
322
|
+
reqPath === '/__castle/context') {
|
|
279
323
|
res.writeHead(404).end();
|
|
280
324
|
return;
|
|
281
325
|
}
|
|
@@ -289,7 +333,8 @@ window.__castleShellOrigin=(function(){
|
|
|
289
333
|
res.writeHead(403).end('content capability does not allow this endpoint');
|
|
290
334
|
return;
|
|
291
335
|
}
|
|
292
|
-
if ((allowedFilesRequest || allowedVendor || allowedFavicon) &&
|
|
336
|
+
if ((allowedFilesRequest || allowedVendor || allowedFavicon) &&
|
|
337
|
+
ideServer.handleHttpRequest(req, res, reqPath))
|
|
293
338
|
return;
|
|
294
339
|
next();
|
|
295
340
|
return;
|
|
@@ -298,7 +343,7 @@ window.__castleShellOrigin=(function(){
|
|
|
298
343
|
reqPath.startsWith('/__castle/ide/') ||
|
|
299
344
|
FAVICON_FILES.some((name) => reqPath === `/${name}`);
|
|
300
345
|
if (reqPath.startsWith('/__castle/') && !publicShellPath && !security.authorizeHttp(req)) {
|
|
301
|
-
|
|
346
|
+
security.rejectHttpAuth(res);
|
|
302
347
|
return;
|
|
303
348
|
}
|
|
304
349
|
// The split-view shell (`/`) + its static assets are served outside
|
|
@@ -317,32 +362,35 @@ window.__castleShellOrigin=(function(){
|
|
|
317
362
|
},
|
|
318
363
|
};
|
|
319
364
|
}
|
|
320
|
-
// The
|
|
321
|
-
//
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
365
|
+
// The serve's own user, fetched once and cached for the serve lifetime so
|
|
366
|
+
// User.getCurrent works in dev. Config may carry only a token: a sandbox
|
|
367
|
+
// starts the serve with CASTLE_TOKEN alone and no config.json, so the userId
|
|
368
|
+
// has to come from `me` there too, not just the username.
|
|
369
|
+
let cachedDevMe;
|
|
370
|
+
async function devMe() {
|
|
371
|
+
if (cachedDevMe !== undefined)
|
|
372
|
+
return cachedDevMe;
|
|
326
373
|
try {
|
|
327
|
-
const res = await castleGraphql('query { me { username } }', {});
|
|
374
|
+
const res = await castleGraphql('query { me { userId username } }', {});
|
|
328
375
|
const me = res.data?.me;
|
|
329
|
-
|
|
376
|
+
cachedDevMe = { userId: me?.userId ?? null, username: me?.username ?? null };
|
|
330
377
|
}
|
|
331
378
|
catch {
|
|
332
|
-
|
|
379
|
+
cachedDevMe = { userId: null, username: null };
|
|
333
380
|
}
|
|
334
|
-
return
|
|
381
|
+
return cachedDevMe;
|
|
335
382
|
}
|
|
336
383
|
async function devHostContext(projectDir) {
|
|
337
384
|
const ctx = readDeckContext(projectDir);
|
|
385
|
+
const me = await devMe();
|
|
338
386
|
return {
|
|
339
387
|
deckId: ctx.deckId ?? null,
|
|
340
388
|
sessionId: null,
|
|
341
|
-
userId: config.getUserId(),
|
|
342
|
-
username:
|
|
389
|
+
userId: config.getUserId() ?? me.userId,
|
|
390
|
+
username: me.username,
|
|
343
391
|
};
|
|
344
392
|
}
|
|
345
|
-
async function handleCastleCommand(ws, projectDir, broadcast, requestId, command, params) {
|
|
393
|
+
async function handleCastleCommand(ws, projectDir, broadcast, multiplayer, multiplayerUrl, requestId, command, params) {
|
|
346
394
|
const ctx = await devHostContext(projectDir);
|
|
347
395
|
// The dev server services data commands via GraphQL but supplies no
|
|
348
396
|
// platformHandler, so platform/capability commands (e.g. passes.purchase)
|
|
@@ -352,11 +400,50 @@ async function handleCastleCommand(ws, projectDir, broadcast, requestId, command
|
|
|
352
400
|
const result = await executeCommand(ctx, command, params, {
|
|
353
401
|
graphqlFetch: castleGraphql,
|
|
354
402
|
showLeaderboard: (payload) => broadcast({ type: 'castle_leaderboard_show', payload }),
|
|
403
|
+
getMultiplayerSession: () => {
|
|
404
|
+
if (!multiplayer || !multiplayerUrl) {
|
|
405
|
+
return Promise.resolve({
|
|
406
|
+
status: 'unavailable',
|
|
407
|
+
url: null,
|
|
408
|
+
nonce: null,
|
|
409
|
+
sessionId: null,
|
|
410
|
+
});
|
|
411
|
+
}
|
|
412
|
+
return Promise.resolve({
|
|
413
|
+
status: 'ok',
|
|
414
|
+
url: multiplayerUrl,
|
|
415
|
+
nonce: multiplayer.mintNonce(devMultiplayerIdentity(ctx)),
|
|
416
|
+
sessionId: multiplayer.sessionId,
|
|
417
|
+
});
|
|
418
|
+
},
|
|
355
419
|
});
|
|
356
420
|
if (ws.readyState === WebSocket.OPEN) {
|
|
357
421
|
ws.send(JSON.stringify({ type: 'castle_command_response', castleSdk: 1, requestId, ...result }));
|
|
358
422
|
}
|
|
359
423
|
}
|
|
424
|
+
function devMultiplayerIdentity(ctx) {
|
|
425
|
+
return {
|
|
426
|
+
userId: ctx.userId ?? 'dev-user',
|
|
427
|
+
username: ctx.username ?? 'Developer',
|
|
428
|
+
isAnonymous: ctx.userId === null,
|
|
429
|
+
};
|
|
430
|
+
}
|
|
431
|
+
function devMultiplayerUrl(req) {
|
|
432
|
+
const base = typeof req.headers.origin === 'string' ? req.headers.origin : null;
|
|
433
|
+
if (!base)
|
|
434
|
+
return null;
|
|
435
|
+
return devMultiplayerUrlFromOrigin(base);
|
|
436
|
+
}
|
|
437
|
+
function devMultiplayerUrlFromOrigin(base) {
|
|
438
|
+
try {
|
|
439
|
+
const url = new URL('/__castle/mp', base);
|
|
440
|
+
url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:';
|
|
441
|
+
return url.toString();
|
|
442
|
+
}
|
|
443
|
+
catch {
|
|
444
|
+
return null;
|
|
445
|
+
}
|
|
446
|
+
}
|
|
360
447
|
function readDeckContext(projectDir) {
|
|
361
448
|
try {
|
|
362
449
|
const raw = fs.readFileSync(path.join(projectDir, 'castle.json'), 'utf8');
|
|
@@ -378,13 +465,12 @@ function readServeJson(projectDir) {
|
|
|
378
465
|
try {
|
|
379
466
|
const raw = fs.readFileSync(path.join(projectDir, '.castle', 'serve.json'), 'utf8');
|
|
380
467
|
const info = JSON.parse(raw);
|
|
381
|
-
if (typeof info.port !== 'number' ||
|
|
382
|
-
typeof info.wsPort !== 'number' ||
|
|
383
|
-
typeof info.pid !== 'number')
|
|
468
|
+
if (typeof info.port !== 'number' || typeof info.pid !== 'number')
|
|
384
469
|
return null;
|
|
385
470
|
return {
|
|
386
471
|
port: info.port,
|
|
387
|
-
wsPort: info.wsPort,
|
|
472
|
+
wsPort: typeof info.wsPort === 'number' ? info.wsPort : undefined,
|
|
473
|
+
wsPath: typeof info.wsPath === 'string' ? info.wsPath : undefined,
|
|
388
474
|
pid: info.pid,
|
|
389
475
|
contentPlayUrl: typeof info.contentPlayUrl === 'string' ? info.contentPlayUrl : undefined,
|
|
390
476
|
};
|
|
@@ -509,11 +595,8 @@ export async function serve(dir, options = {}) {
|
|
|
509
595
|
}
|
|
510
596
|
}
|
|
511
597
|
const startPort = parseInt(options.port ?? String(DEFAULT_PORT), 10);
|
|
512
|
-
const
|
|
513
|
-
|
|
514
|
-
: await findFreePorts(startPort);
|
|
515
|
-
const localContentPorts = await findLocalContentPorts(port + 2, new Set([port, wsPort]));
|
|
516
|
-
const security = new ServeSecurity(port, localContentPorts);
|
|
598
|
+
const port = options.port ? startPort : await findFreePort(startPort);
|
|
599
|
+
const security = new ServeSecurity(port);
|
|
517
600
|
// Local WebSocket server for SDK communication
|
|
518
601
|
const castleDir = path.join(projectDir, '.castle');
|
|
519
602
|
if (!fs.existsSync(castleDir))
|
|
@@ -546,10 +629,27 @@ export async function serve(dir, options = {}) {
|
|
|
546
629
|
// Terminal close: exit through the handlers so child agent processes die
|
|
547
630
|
// with the serve instead of orphaning.
|
|
548
631
|
process.on('SIGHUP', () => process.exit());
|
|
632
|
+
let broadcastDevLog = () => undefined;
|
|
633
|
+
const devSession = resolveServerConfig(projectDir)
|
|
634
|
+
? await startDevSessionServer({
|
|
635
|
+
projectDir,
|
|
636
|
+
log: (level, text) => {
|
|
637
|
+
const line = `[server] ${text}`;
|
|
638
|
+
appendCapped(logFile, `${line}\n`);
|
|
639
|
+
if (level === 'error')
|
|
640
|
+
process.stderr.write(`${line}\n`);
|
|
641
|
+
else
|
|
642
|
+
process.stdout.write(`${line}\n`);
|
|
643
|
+
broadcastDevLog({ type: 'server_log', level, text: line });
|
|
644
|
+
},
|
|
645
|
+
})
|
|
646
|
+
: null;
|
|
647
|
+
process.on('exit', () => devSession?.shutdownNow());
|
|
549
648
|
// The WS server forwards `restart` to the browser, but it also needs the
|
|
550
649
|
// Vite instance so it can drop transform caches first (see invalidateModuleCaches).
|
|
551
650
|
const viteHolder = { vite: null };
|
|
552
|
-
const { broadcast } = startWSServer(
|
|
651
|
+
const { broadcast, handleUpgrade: handleCastleUpgrade } = startWSServer(projectDir, logFile, screenshotsDir, viteHolder, security, devSession);
|
|
652
|
+
broadcastDevLog = broadcast;
|
|
553
653
|
// The deck root `/` serves a split-view shell: the deck in an iframe plus a
|
|
554
654
|
// toggle button for an xterm.js terminal. The terminal's PTY is lazy -- it
|
|
555
655
|
// spawns only when a browser first opens the PTY WebSocket.
|
|
@@ -571,6 +671,18 @@ export async function serve(dir, options = {}) {
|
|
|
571
671
|
authorizeUpgrade: (req) => security.consumeTicket(req, 'pty'),
|
|
572
672
|
});
|
|
573
673
|
process.on('exit', () => ideServer.shutdown());
|
|
674
|
+
const upstreamHost = !options.host || options.host === 'localhost'
|
|
675
|
+
? 'localhost'
|
|
676
|
+
: options.host === '0.0.0.0'
|
|
677
|
+
? '127.0.0.1'
|
|
678
|
+
: options.host === '::'
|
|
679
|
+
? '::1'
|
|
680
|
+
: options.host;
|
|
681
|
+
const localContentServers = await startLocalContentServers(upstreamHost, port, security, new Set([port]));
|
|
682
|
+
process.on('exit', () => {
|
|
683
|
+
for (const server of localContentServers)
|
|
684
|
+
server.close();
|
|
685
|
+
});
|
|
574
686
|
// The agent panel backend: router conversation + background task agents,
|
|
575
687
|
// state under .castle/agent/. Its WebSocket shares Vite's HTTP server.
|
|
576
688
|
const agentServer = createAgentServer({
|
|
@@ -610,59 +722,71 @@ export async function serve(dir, options = {}) {
|
|
|
610
722
|
open: options.open ? true : undefined,
|
|
611
723
|
hmr: false,
|
|
612
724
|
proxy: {
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
725
|
+
...(devSession
|
|
726
|
+
? {
|
|
727
|
+
'/__castle/mp': {
|
|
728
|
+
target: `ws://127.0.0.1:${devSession.port}`,
|
|
729
|
+
ws: true,
|
|
730
|
+
},
|
|
731
|
+
}
|
|
732
|
+
: {}),
|
|
617
733
|
},
|
|
618
734
|
fs: {
|
|
619
735
|
strict: true,
|
|
620
736
|
allow: [projectDir],
|
|
621
|
-
deny: [
|
|
737
|
+
deny: [
|
|
738
|
+
'.env',
|
|
739
|
+
'.env.*',
|
|
740
|
+
'*.pem',
|
|
741
|
+
'*.key',
|
|
742
|
+
'*.crt',
|
|
743
|
+
'.castle',
|
|
744
|
+
'.castle/**',
|
|
745
|
+
'.git',
|
|
746
|
+
'.git/**',
|
|
747
|
+
],
|
|
622
748
|
},
|
|
623
749
|
},
|
|
624
750
|
logLevel: 'info',
|
|
625
751
|
});
|
|
626
752
|
viteHolder.vite = vite;
|
|
753
|
+
// Castle's control socket shares the public Vite listener. Keeping every
|
|
754
|
+
// externally-reachable deck endpoint on P means adjacent decks may safely
|
|
755
|
+
// use P+1; only Safari's loopback content proxies need extra listeners, and
|
|
756
|
+
// those are OS-assigned ephemeral ports.
|
|
757
|
+
if (vite.httpServer) {
|
|
758
|
+
vite.httpServer.on('upgrade', (req, socket, head) => {
|
|
759
|
+
if (handleCastleUpgrade(req, socket, head))
|
|
760
|
+
return;
|
|
761
|
+
if (!ideServer.handleUpgrade(req, socket, head)) {
|
|
762
|
+
agentServer.handleUpgrade(req, socket, head);
|
|
763
|
+
}
|
|
764
|
+
});
|
|
765
|
+
}
|
|
627
766
|
// File changes from ANY source (editors, agents, terminal) become one
|
|
628
767
|
// coalesced `files_changed` broadcast; consumers decide what to reload.
|
|
629
768
|
installFilesChangedWatcher({
|
|
630
769
|
vite,
|
|
631
770
|
projectDir,
|
|
632
|
-
broadcast
|
|
771
|
+
broadcast: (message) => {
|
|
772
|
+
devSession?.handleFilesChanged(message);
|
|
773
|
+
broadcast(message);
|
|
774
|
+
},
|
|
633
775
|
invalidate: (paths) => invalidateModuleCaches(vite, paths),
|
|
634
776
|
log: (line) => appendCapped(logFile, line),
|
|
635
777
|
});
|
|
636
778
|
// Bring content up first so `--open` cannot race an iframe against a port
|
|
637
779
|
// that is not listening yet. Vite opens the shell from inside `vite.listen()`.
|
|
638
|
-
const upstreamHost = !options.host || options.host === 'localhost'
|
|
639
|
-
? 'localhost'
|
|
640
|
-
: options.host === '0.0.0.0'
|
|
641
|
-
? '127.0.0.1'
|
|
642
|
-
: options.host === '::'
|
|
643
|
-
? '::1'
|
|
644
|
-
: options.host;
|
|
645
|
-
const localContentServers = await startLocalContentServers(upstreamHost, port, localContentPorts, security);
|
|
646
|
-
process.on('exit', () => {
|
|
647
|
-
for (const server of localContentServers)
|
|
648
|
-
server.close();
|
|
649
|
-
});
|
|
650
780
|
await vite.listen();
|
|
651
781
|
fs.writeFileSync(serveJsonPath, JSON.stringify({
|
|
652
782
|
port,
|
|
653
|
-
|
|
783
|
+
// Kept for older CLI commands: they connect to this port's root path.
|
|
784
|
+
// New clients use wsPath. Both routes reach the same noServer WSS.
|
|
785
|
+
wsPort: port,
|
|
786
|
+
wsPath: '/__castle/ws',
|
|
654
787
|
pid: process.pid,
|
|
655
788
|
contentPlayUrl: security.localContentOrigin('play'),
|
|
656
789
|
}) + '\n');
|
|
657
|
-
// The PTY WebSocket upgrade is handled directly on Vite's HTTP server rather
|
|
658
|
-
// than through Vite's proxy (Vite's ws proxy didn't forward this path).
|
|
659
|
-
if (vite.httpServer) {
|
|
660
|
-
vite.httpServer.on('upgrade', (req, socket, head) => {
|
|
661
|
-
if (!ideServer.handleUpgrade(req, socket, head)) {
|
|
662
|
-
agentServer.handleUpgrade(req, socket, head);
|
|
663
|
-
}
|
|
664
|
-
});
|
|
665
|
-
}
|
|
666
790
|
vite.printUrls();
|
|
667
791
|
}
|
|
668
792
|
// `restart` does a full browser reload, but Vite keeps transformed modules
|
|
@@ -790,25 +914,33 @@ async function serveDetached(projectDir, options) {
|
|
|
790
914
|
}
|
|
791
915
|
throw new Error(`Detached serve did not write ${serveJsonPath} within 15s; check ${logPath} for startup errors.`);
|
|
792
916
|
}
|
|
793
|
-
function startWSServer(
|
|
794
|
-
//
|
|
795
|
-
//
|
|
796
|
-
//
|
|
797
|
-
//
|
|
917
|
+
function startWSServer(projectDir, logFile, screenshotsDir, viteHolder, security, multiplayer) {
|
|
918
|
+
// The control socket is upgraded directly on Vite's HTTP server. Browser
|
|
919
|
+
// clients use the named path and a one-use ticket. The root path is accepted
|
|
920
|
+
// only from loopback clients with no Origin so older CLI versions can read
|
|
921
|
+
// wsPort from a new serve.json and continue to connect during rollout.
|
|
798
922
|
const wss = new WebSocketServer({
|
|
799
|
-
|
|
800
|
-
host: '127.0.0.1',
|
|
923
|
+
noServer: true,
|
|
801
924
|
maxPayload: 12 * 1024 * 1024,
|
|
802
|
-
verifyClient: ({ req }, done) => {
|
|
803
|
-
// Node-side CLI clients are loopback and carry no browser Origin. Browser clients
|
|
804
|
-
// arrive through Vite's loopback proxy but must prove both origin and a one-use ticket.
|
|
805
|
-
if (!req.headers.origin) {
|
|
806
|
-
done(req.socket.remoteAddress === '127.0.0.1' || req.socket.remoteAddress === '::1');
|
|
807
|
-
return;
|
|
808
|
-
}
|
|
809
|
-
done(isSameOriginUpgrade(req) && security.consumeTicket(req, 'serve'));
|
|
810
|
-
},
|
|
811
925
|
});
|
|
926
|
+
const handleUpgrade = (req, socket, head) => {
|
|
927
|
+
const pathname = new URL(req.url || '/', 'http://localhost').pathname;
|
|
928
|
+
const hasOrigin = Boolean(req.headers.origin);
|
|
929
|
+
const isNamedPath = pathname === '/__castle/ws';
|
|
930
|
+
const isLegacyCliPath = pathname === '/' && !hasOrigin;
|
|
931
|
+
if (!isNamedPath && !isLegacyCliPath)
|
|
932
|
+
return false;
|
|
933
|
+
const loopback = req.socket.remoteAddress === '127.0.0.1' || req.socket.remoteAddress === '::1';
|
|
934
|
+
const authorized = hasOrigin
|
|
935
|
+
? isNamedPath && isSameOriginUpgrade(req) && security.consumeTicket(req, 'serve')
|
|
936
|
+
: loopback;
|
|
937
|
+
if (!authorized) {
|
|
938
|
+
socket.destroy();
|
|
939
|
+
return true;
|
|
940
|
+
}
|
|
941
|
+
wss.handleUpgrade(req, socket, head, (ws) => wss.emit('connection', ws, req));
|
|
942
|
+
return true;
|
|
943
|
+
};
|
|
812
944
|
const clients = new Set();
|
|
813
945
|
const broadcast = (msg) => {
|
|
814
946
|
const data = JSON.stringify(msg);
|
|
@@ -828,8 +960,9 @@ function startWSServer(port, projectDir, logFile, screenshotsDir, viteHolder, se
|
|
|
828
960
|
clearTimeout(pending.timeout);
|
|
829
961
|
requestOrigins.delete(requestId);
|
|
830
962
|
};
|
|
831
|
-
wss.on('connection', (ws) => {
|
|
963
|
+
wss.on('connection', (ws, req) => {
|
|
832
964
|
clients.add(ws);
|
|
965
|
+
const multiplayerUrl = devMultiplayerUrl(req);
|
|
833
966
|
ws.on('message', (raw) => {
|
|
834
967
|
try {
|
|
835
968
|
const text = Array.isArray(raw)
|
|
@@ -839,19 +972,16 @@ function startWSServer(port, projectDir, logFile, screenshotsDir, viteHolder, se
|
|
|
839
972
|
: Buffer.from(raw).toString('utf8');
|
|
840
973
|
let msg = JSON.parse(text);
|
|
841
974
|
let bridgeRole = null;
|
|
975
|
+
let bridgeContentOrigin = null;
|
|
842
976
|
if (msg.type === 'deck_bridge') {
|
|
843
977
|
if ((msg.role !== 'edit' && msg.role !== 'play') ||
|
|
844
978
|
!msg.message ||
|
|
845
979
|
typeof msg.message !== 'object')
|
|
846
980
|
return;
|
|
847
981
|
bridgeRole = msg.role;
|
|
982
|
+
bridgeContentOrigin = trustedBridgeContentOrigin(security, req, bridgeRole, msg.contentOrigin);
|
|
848
983
|
msg = msg.message;
|
|
849
|
-
const allowed = new Set([
|
|
850
|
-
'log',
|
|
851
|
-
'screenshot_response',
|
|
852
|
-
'write_file',
|
|
853
|
-
'castle_command',
|
|
854
|
-
]);
|
|
984
|
+
const allowed = new Set(['log', 'screenshot_response', 'write_file', 'castle_command']);
|
|
855
985
|
if (!allowed.has(String(msg.type)))
|
|
856
986
|
return;
|
|
857
987
|
}
|
|
@@ -979,7 +1109,11 @@ function startWSServer(port, projectDir, logFile, screenshotsDir, viteHolder, se
|
|
|
979
1109
|
// token, then replies to just this socket. See castle-web-sdk's
|
|
980
1110
|
// transport.ts (local channel) + host.ts.
|
|
981
1111
|
if (msg.type === 'castle_command' && typeof msg.requestId === 'string') {
|
|
982
|
-
|
|
1112
|
+
const commandMultiplayerUrl = bridgeRole
|
|
1113
|
+
? devMultiplayerUrlFromOrigin(bridgeContentOrigin ??
|
|
1114
|
+
security.contentOrigins(req)[bridgeRole === 'edit' ? 'editOrigin' : 'playOrigin'])
|
|
1115
|
+
: multiplayerUrl;
|
|
1116
|
+
void handleCastleCommand(ws, projectDir, broadcast, multiplayer, commandMultiplayerUrl, msg.requestId, msg.command, msg.params);
|
|
983
1117
|
}
|
|
984
1118
|
}
|
|
985
1119
|
catch {
|
|
@@ -995,7 +1129,34 @@ function startWSServer(port, projectDir, logFile, screenshotsDir, viteHolder, se
|
|
|
995
1129
|
}
|
|
996
1130
|
});
|
|
997
1131
|
});
|
|
998
|
-
return { wss, broadcast };
|
|
1132
|
+
return { wss, broadcast, handleUpgrade };
|
|
1133
|
+
}
|
|
1134
|
+
function normalizedHttpOrigin(value) {
|
|
1135
|
+
if (typeof value !== 'string')
|
|
1136
|
+
return null;
|
|
1137
|
+
try {
|
|
1138
|
+
const url = new URL(value);
|
|
1139
|
+
if (url.protocol !== 'http:' && url.protocol !== 'https:')
|
|
1140
|
+
return null;
|
|
1141
|
+
return url.origin;
|
|
1142
|
+
}
|
|
1143
|
+
catch {
|
|
1144
|
+
return null;
|
|
1145
|
+
}
|
|
1146
|
+
}
|
|
1147
|
+
function trustedBridgeContentOrigin(security, request, role, value) {
|
|
1148
|
+
const origin = normalizedHttpOrigin(value);
|
|
1149
|
+
if (!origin)
|
|
1150
|
+
return null;
|
|
1151
|
+
if (origin === security.localContentOrigin(role) || origin === request.headers.origin)
|
|
1152
|
+
return origin;
|
|
1153
|
+
const url = new URL(origin);
|
|
1154
|
+
const synthetic = {
|
|
1155
|
+
headers: { ...request.headers, host: url.host },
|
|
1156
|
+
socket: request.socket,
|
|
1157
|
+
url: role === 'play' ? '/index.html?edit=0' : '/index.html',
|
|
1158
|
+
};
|
|
1159
|
+
return security.verifyContentRequest(synthetic) === role ? origin : null;
|
|
999
1160
|
}
|
|
1000
1161
|
function writeProjectFile(projectDir, requestedPath, contents) {
|
|
1001
1162
|
if (typeof requestedPath !== 'string' || requestedPath.trim() === '') {
|
package/dist/serveSecurity.d.ts
CHANGED
|
@@ -2,6 +2,9 @@ import type * as http from 'http';
|
|
|
2
2
|
export type ContentRole = 'edit' | 'play';
|
|
3
3
|
export type SocketEndpoint = 'serve' | 'pty' | 'agent';
|
|
4
4
|
export type LocalContentPorts = Record<ContentRole, number>;
|
|
5
|
+
export declare const SERVE_AUTH_FAILURE_HEADER = "x-castle-serve-auth";
|
|
6
|
+
export declare const SERVE_AUTH_FAILURE_VALUE = "invalid";
|
|
7
|
+
export declare const MOBILE_HOST_PROTOCOL = "2";
|
|
5
8
|
export declare function mintContentGrantLabel(grant: {
|
|
6
9
|
role: ContentRole;
|
|
7
10
|
publicPort: number;
|
|
@@ -11,14 +14,16 @@ export declare function mintContentGrantLabel(grant: {
|
|
|
11
14
|
}, signingKey: string): string;
|
|
12
15
|
export declare class ServeSecurity {
|
|
13
16
|
private readonly publicPort;
|
|
14
|
-
private readonly localContentPorts;
|
|
15
17
|
readonly serveToken: string;
|
|
16
18
|
private readonly contentProxyToken;
|
|
17
19
|
private readonly signingKey;
|
|
18
20
|
private readonly serveNonce;
|
|
19
21
|
private readonly tickets;
|
|
22
|
+
private localContentPorts;
|
|
20
23
|
constructor(publicPort: number, localContentPorts?: LocalContentPorts);
|
|
24
|
+
setLocalContentPorts(ports: LocalContentPorts): void;
|
|
21
25
|
authorizeHttp(req: http.IncomingMessage): boolean;
|
|
26
|
+
rejectHttpAuth(res: http.ServerResponse): void;
|
|
22
27
|
issueTicket(endpoint: SocketEndpoint): string;
|
|
23
28
|
consumeTicket(req: http.IncomingMessage, endpoint: SocketEndpoint): boolean;
|
|
24
29
|
private pruneTickets;
|
|
@@ -33,5 +38,6 @@ export declare class ServeSecurity {
|
|
|
33
38
|
compatibilityContentRole(req: http.IncomingMessage): ContentRole | null;
|
|
34
39
|
shellOrigin(req: http.IncomingMessage): string;
|
|
35
40
|
private mintContentLabel;
|
|
41
|
+
private requestsIsolatedContentOrigins;
|
|
36
42
|
private contentMac;
|
|
37
43
|
}
|