castle-web-cli 0.4.149 → 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.
Files changed (44) hide show
  1. package/dist/api.d.ts +14 -0
  2. package/dist/api.js +18 -0
  3. package/dist/castle-host/host.d.ts +17 -0
  4. package/dist/castle-host/host.js +10 -7
  5. package/dist/castleJson.d.ts +15 -0
  6. package/dist/castleJson.js +36 -0
  7. package/dist/devSessionChild.d.ts +1 -0
  8. package/dist/devSessionChild.js +129 -0
  9. package/dist/devSessionServer.d.ts +19 -0
  10. package/dist/devSessionServer.js +511 -0
  11. package/dist/index.js +8 -8
  12. package/dist/init.js +9 -1
  13. package/dist/list-decks.js +7 -6
  14. package/dist/preview.d.ts +1 -1
  15. package/dist/preview.js +4 -2
  16. package/dist/save-deck.js +63 -14
  17. package/dist/serve.js +220 -85
  18. package/dist/serveSecurity.d.ts +5 -1
  19. package/dist/serveSecurity.js +48 -10
  20. package/dist/serverBundle.d.ts +8 -0
  21. package/dist/serverBundle.js +82 -0
  22. package/dist/shell/assets/{index-BzFzFtEP.js → index-Dlhc3eZW.js} +42 -42
  23. package/dist/shell/assets/index-DwezawBs.css +1 -0
  24. package/dist/shell/index.html +2 -2
  25. package/kits/blank/.castle/agent/children.json +1 -0
  26. package/kits/blank/.castle/agent/messages.json +9 -0
  27. package/kits/blank/.castle/agent/pending-sends.json +1 -0
  28. package/kits/blank/.castle/agent/tasks/index.md +2 -0
  29. package/kits/blank/.castle/docs/platform.md +36 -0
  30. package/kits/blank/castle.json +5 -2
  31. package/kits/blank/node_modules/.vite/deps/_metadata.json +8 -0
  32. package/kits/blank/node_modules/.vite/deps/package.json +3 -0
  33. package/kits/physics-2d/behaviors/Collider.jsx +1 -2
  34. package/kits/physics-2d/behaviors/Joints.jsx +1 -1
  35. package/kits/physics-2d/castle.json +1 -1
  36. package/kits/physics-2d/editors/BlueprintLibrary.jsx +33 -3
  37. package/kits/physics-2d/editors/SceneEditor.jsx +171 -57
  38. package/kits/physics-2d/editors/SingleEditor.jsx +6 -0
  39. package/kits/physics-2d/engine/blueprint.js +106 -14
  40. package/kits/physics-2d/engine/scene.js +9 -2
  41. package/kits/physics-2d/engine/ui.jsx +30 -2
  42. package/kits/physics-2d/engine/ui.module.css +59 -0
  43. package/package.json +1 -1
  44. package/dist/shell/assets/index-DN8HQBnW.css +0 -1
package/dist/save-deck.js CHANGED
@@ -6,7 +6,9 @@ import { nanoid } from 'nanoid';
6
6
  import * as api from './api.js';
7
7
  import * as config from './config.js';
8
8
  import { bundleProject } from './bundle.js';
9
+ import { resolveServerConfig } from './castleJson.js';
9
10
  import { COVER_FILE } from './ide.js';
11
+ import { buildServerBundle } from './serverBundle.js';
10
12
  // `imports/` is derived state like node_modules: a dependency's files belong to
11
13
  // the deck that published them, and castle.json's import pins are enough to fetch
12
14
  // them again -- so they neither bloat this deck's archive nor get republished as
@@ -57,30 +59,76 @@ export async function archiveSource(projectDir) {
57
59
  }
58
60
  }
59
61
  }
62
+ async function uploadPresignedFile(uploadConfig, file, contentType, timeoutMs, label) {
63
+ const formData = new FormData();
64
+ formData.append('Content-Type', contentType);
65
+ for (const [key, value] of Object.entries(uploadConfig.postFields)) {
66
+ formData.append(key, String(value));
67
+ }
68
+ formData.append('file', file);
69
+ const response = await fetch(uploadConfig.postUrl, {
70
+ method: 'POST',
71
+ body: formData,
72
+ signal: AbortSignal.timeout(timeoutMs),
73
+ });
74
+ if (response.status >= 300)
75
+ throw new Error(`${label} failed: HTTP ${response.status}`);
76
+ }
60
77
  async function uploadSource(projectDir, deckId) {
61
78
  const archive = await archiveSource(projectDir);
62
79
  const sizeKB = archive.length / 1024;
63
80
  console.log(`Source archive: ${sizeKB.toFixed(1)}KB`);
64
81
  const uploadConfig = await api.createWebDeckSourceUploadConfig(deckId);
65
- const formData = new FormData();
66
- formData.append('Content-Type', 'application/gzip');
67
- for (const [k, v] of Object.entries(uploadConfig.postFields)) {
68
- formData.append(k, String(v));
69
- }
70
82
  // FormData expects a Blob; copy the Buffer's bytes so we don't share the underlying ArrayBuffer.
71
83
  const view = new Uint8Array(archive.byteLength);
72
84
  view.set(archive);
73
- formData.append('file', new Blob([view], { type: 'application/gzip' }));
74
- const s3Res = await fetch(uploadConfig.postUrl, {
75
- method: 'POST',
76
- body: formData,
77
- signal: AbortSignal.timeout(60000),
78
- });
79
- if (s3Res.status >= 300) {
80
- throw new Error(`Source upload failed: HTTP ${s3Res.status}`);
81
- }
85
+ await uploadPresignedFile(uploadConfig, new Blob([view], { type: 'application/gzip' }), 'application/gzip', 60_000, 'Source upload');
82
86
  await api.saveWebDeckSource(deckId, uploadConfig.uploadId);
83
87
  }
88
+ const SERVER_BUNDLE_STATE = path.join('.castle', 'published-server-bundle.json');
89
+ function readPublishedServerBundleState(projectDir) {
90
+ try {
91
+ const value = JSON.parse(fs.readFileSync(path.join(projectDir, SERVER_BUNDLE_STATE), 'utf8'));
92
+ return typeof value.deckId === 'string' && typeof value.sha256 === 'string'
93
+ ? { deckId: value.deckId, sha256: value.sha256 }
94
+ : null;
95
+ }
96
+ catch {
97
+ return null;
98
+ }
99
+ }
100
+ function writePublishedServerBundleState(projectDir, state) {
101
+ const file = path.join(projectDir, SERVER_BUNDLE_STATE);
102
+ fs.mkdirSync(path.dirname(file), { recursive: true });
103
+ fs.writeFileSync(file, `${JSON.stringify(state, null, 2)}\n`, 'utf8');
104
+ }
105
+ async function publishServerBundle(projectDir, deckId) {
106
+ const serverConfig = resolveServerConfig(projectDir);
107
+ if (!serverConfig) {
108
+ const prior = readPublishedServerBundleState(projectDir);
109
+ if (prior?.deckId !== deckId) {
110
+ console.log('Server bundle skipped: no server entry found.');
111
+ return;
112
+ }
113
+ await api.saveCauldronServerBundle(deckId, null);
114
+ fs.rmSync(path.join(projectDir, SERVER_BUNDLE_STATE), { force: true });
115
+ console.log('Cleared the previously published server bundle (no server entry found).');
116
+ return;
117
+ }
118
+ console.log(`Bundling server (${serverConfig.entry})...`);
119
+ const bundle = await buildServerBundle(projectDir);
120
+ if (!bundle)
121
+ throw new Error('Server entry disappeared while bundling.');
122
+ console.log(`Server bundle size: ${(bundle.sizeBytes / 1024).toFixed(1)}KB`);
123
+ const uploadConfig = await api.createCauldronServerBundleUploadConfig(deckId);
124
+ await uploadPresignedFile(uploadConfig, new Blob([bundle.code], { type: 'application/javascript' }), 'application/javascript', 60_000, 'Server bundle upload');
125
+ await api.saveCauldronServerBundle(deckId, uploadConfig.uploadId, {
126
+ tickRate: serverConfig.tickRate,
127
+ maxPlayers: serverConfig.maxPlayers,
128
+ });
129
+ writePublishedServerBundleState(projectDir, { deckId, sha256: bundle.sha256 });
130
+ console.log(`Server bundle published (sha256 ${bundle.sha256}).`);
131
+ }
84
132
  // Publish the deck's local cover, if it has one, and return the file id for the
85
133
  // card. The editor writes `preview.png` as you play (see the serve's cover
86
134
  // endpoint); this is the moment it becomes public.
@@ -273,6 +321,7 @@ export async function saveDeck(dir, opts = {}) {
273
321
  else {
274
322
  console.log(`Saved "${title}" to Castle.`);
275
323
  }
324
+ await publishServerBundle(projectDir, result.deckId);
276
325
  console.log('Uploading source archive...');
277
326
  await uploadSource(projectDir, result.deckId);
278
327
  console.log('Source archive saved.');
package/dist/serve.js CHANGED
@@ -19,6 +19,8 @@ import { graphql as castleGraphql } from './api.js';
19
19
  import { executeCommand } from './castle-host/host.js';
20
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 findFreePorts(startPort) {
50
- for (let p = startPort; p < startPort + 100; p += 2) {
51
- if ((await isPortFree(p)) && (await isPortFree(p + 1))) {
52
- return { port: p, wsPort: p + 1 };
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
- if (free.length !== 2)
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, port, role, security) {
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
- if (!isViteClientUpgrade(req)) {
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
- server.listen(port, '127.0.0.1', () => {
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
- resolve(server);
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
- async function startLocalContentServers(upstreamHost, upstreamPort, ports, security) {
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 [role, port] of [
148
- ['edit', ports.edit],
149
- ['play', ports.play],
150
- ]) {
151
- servers.push(await listenLocalContentServer(upstreamHost, upstreamPort, port, role, security));
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) {
@@ -277,10 +300,14 @@ window.__castleShellOrigin=(function(){
277
300
  return;
278
301
  }
279
302
  if (reqPath === '/__castle/ws-ticket') {
280
- if (content || req.method !== 'POST' || !security.authorizeHttp(req)) {
303
+ if (content || req.method !== 'POST') {
281
304
  res.writeHead(403).end();
282
305
  return;
283
306
  }
307
+ if (!security.authorizeHttp(req)) {
308
+ security.rejectHttpAuth(res);
309
+ return;
310
+ }
284
311
  const endpoint = new URL(req.url || '/', 'http://localhost').searchParams.get('endpoint');
285
312
  if (endpoint !== 'serve' && endpoint !== 'pty' && endpoint !== 'agent') {
286
313
  res.writeHead(400).end('invalid endpoint');
@@ -316,7 +343,7 @@ window.__castleShellOrigin=(function(){
316
343
  reqPath.startsWith('/__castle/ide/') ||
317
344
  FAVICON_FILES.some((name) => reqPath === `/${name}`);
318
345
  if (reqPath.startsWith('/__castle/') && !publicShellPath && !security.authorizeHttp(req)) {
319
- res.writeHead(403).end();
346
+ security.rejectHttpAuth(res);
320
347
  return;
321
348
  }
322
349
  // The split-view shell (`/`) + its static assets are served outside
@@ -363,7 +390,7 @@ async function devHostContext(projectDir) {
363
390
  username: me.username,
364
391
  };
365
392
  }
366
- async function handleCastleCommand(ws, projectDir, broadcast, requestId, command, params) {
393
+ async function handleCastleCommand(ws, projectDir, broadcast, multiplayer, multiplayerUrl, requestId, command, params) {
367
394
  const ctx = await devHostContext(projectDir);
368
395
  // The dev server services data commands via GraphQL but supplies no
369
396
  // platformHandler, so platform/capability commands (e.g. passes.purchase)
@@ -373,11 +400,50 @@ async function handleCastleCommand(ws, projectDir, broadcast, requestId, command
373
400
  const result = await executeCommand(ctx, command, params, {
374
401
  graphqlFetch: castleGraphql,
375
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
+ },
376
419
  });
377
420
  if (ws.readyState === WebSocket.OPEN) {
378
421
  ws.send(JSON.stringify({ type: 'castle_command_response', castleSdk: 1, requestId, ...result }));
379
422
  }
380
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
+ }
381
447
  function readDeckContext(projectDir) {
382
448
  try {
383
449
  const raw = fs.readFileSync(path.join(projectDir, 'castle.json'), 'utf8');
@@ -399,13 +465,12 @@ function readServeJson(projectDir) {
399
465
  try {
400
466
  const raw = fs.readFileSync(path.join(projectDir, '.castle', 'serve.json'), 'utf8');
401
467
  const info = JSON.parse(raw);
402
- if (typeof info.port !== 'number' ||
403
- typeof info.wsPort !== 'number' ||
404
- typeof info.pid !== 'number')
468
+ if (typeof info.port !== 'number' || typeof info.pid !== 'number')
405
469
  return null;
406
470
  return {
407
471
  port: info.port,
408
- wsPort: info.wsPort,
472
+ wsPort: typeof info.wsPort === 'number' ? info.wsPort : undefined,
473
+ wsPath: typeof info.wsPath === 'string' ? info.wsPath : undefined,
409
474
  pid: info.pid,
410
475
  contentPlayUrl: typeof info.contentPlayUrl === 'string' ? info.contentPlayUrl : undefined,
411
476
  };
@@ -530,11 +595,8 @@ export async function serve(dir, options = {}) {
530
595
  }
531
596
  }
532
597
  const startPort = parseInt(options.port ?? String(DEFAULT_PORT), 10);
533
- const { port, wsPort } = options.port
534
- ? { port: startPort, wsPort: startPort + 1 }
535
- : await findFreePorts(startPort);
536
- const localContentPorts = await findLocalContentPorts(port + 2, new Set([port, wsPort]));
537
- const security = new ServeSecurity(port, localContentPorts);
598
+ const port = options.port ? startPort : await findFreePort(startPort);
599
+ const security = new ServeSecurity(port);
538
600
  // Local WebSocket server for SDK communication
539
601
  const castleDir = path.join(projectDir, '.castle');
540
602
  if (!fs.existsSync(castleDir))
@@ -567,10 +629,27 @@ export async function serve(dir, options = {}) {
567
629
  // Terminal close: exit through the handlers so child agent processes die
568
630
  // with the serve instead of orphaning.
569
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());
570
648
  // The WS server forwards `restart` to the browser, but it also needs the
571
649
  // Vite instance so it can drop transform caches first (see invalidateModuleCaches).
572
650
  const viteHolder = { vite: null };
573
- const { broadcast } = startWSServer(wsPort, projectDir, logFile, screenshotsDir, viteHolder, security);
651
+ const { broadcast, handleUpgrade: handleCastleUpgrade } = startWSServer(projectDir, logFile, screenshotsDir, viteHolder, security, devSession);
652
+ broadcastDevLog = broadcast;
574
653
  // The deck root `/` serves a split-view shell: the deck in an iframe plus a
575
654
  // toggle button for an xterm.js terminal. The terminal's PTY is lazy -- it
576
655
  // spawns only when a browser first opens the PTY WebSocket.
@@ -592,6 +671,18 @@ export async function serve(dir, options = {}) {
592
671
  authorizeUpgrade: (req) => security.consumeTicket(req, 'pty'),
593
672
  });
594
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
+ });
595
686
  // The agent panel backend: router conversation + background task agents,
596
687
  // state under .castle/agent/. Its WebSocket shares Vite's HTTP server.
597
688
  const agentServer = createAgentServer({
@@ -631,10 +722,14 @@ export async function serve(dir, options = {}) {
631
722
  open: options.open ? true : undefined,
632
723
  hmr: false,
633
724
  proxy: {
634
- '/__castle/ws': {
635
- target: `ws://localhost:${wsPort}`,
636
- ws: true,
637
- },
725
+ ...(devSession
726
+ ? {
727
+ '/__castle/mp': {
728
+ target: `ws://127.0.0.1:${devSession.port}`,
729
+ ws: true,
730
+ },
731
+ }
732
+ : {}),
638
733
  },
639
734
  fs: {
640
735
  strict: true,
@@ -655,45 +750,43 @@ export async function serve(dir, options = {}) {
655
750
  logLevel: 'info',
656
751
  });
657
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
+ }
658
766
  // File changes from ANY source (editors, agents, terminal) become one
659
767
  // coalesced `files_changed` broadcast; consumers decide what to reload.
660
768
  installFilesChangedWatcher({
661
769
  vite,
662
770
  projectDir,
663
- broadcast,
771
+ broadcast: (message) => {
772
+ devSession?.handleFilesChanged(message);
773
+ broadcast(message);
774
+ },
664
775
  invalidate: (paths) => invalidateModuleCaches(vite, paths),
665
776
  log: (line) => appendCapped(logFile, line),
666
777
  });
667
778
  // Bring content up first so `--open` cannot race an iframe against a port
668
779
  // that is not listening yet. Vite opens the shell from inside `vite.listen()`.
669
- const upstreamHost = !options.host || options.host === 'localhost'
670
- ? 'localhost'
671
- : options.host === '0.0.0.0'
672
- ? '127.0.0.1'
673
- : options.host === '::'
674
- ? '::1'
675
- : options.host;
676
- const localContentServers = await startLocalContentServers(upstreamHost, port, localContentPorts, security);
677
- process.on('exit', () => {
678
- for (const server of localContentServers)
679
- server.close();
680
- });
681
780
  await vite.listen();
682
781
  fs.writeFileSync(serveJsonPath, JSON.stringify({
683
782
  port,
684
- wsPort,
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',
685
787
  pid: process.pid,
686
788
  contentPlayUrl: security.localContentOrigin('play'),
687
789
  }) + '\n');
688
- // The PTY WebSocket upgrade is handled directly on Vite's HTTP server rather
689
- // than through Vite's proxy (Vite's ws proxy didn't forward this path).
690
- if (vite.httpServer) {
691
- vite.httpServer.on('upgrade', (req, socket, head) => {
692
- if (!ideServer.handleUpgrade(req, socket, head)) {
693
- agentServer.handleUpgrade(req, socket, head);
694
- }
695
- });
696
- }
697
790
  vite.printUrls();
698
791
  }
699
792
  // `restart` does a full browser reload, but Vite keeps transformed modules
@@ -821,25 +914,33 @@ async function serveDetached(projectDir, options) {
821
914
  }
822
915
  throw new Error(`Detached serve did not write ${serveJsonPath} within 15s; check ${logPath} for startup errors.`);
823
916
  }
824
- function startWSServer(port, projectDir, logFile, screenshotsDir, viteHolder, security) {
825
- // Bind to loopback: the only reachers are same-container callers — the Vite proxy
826
- // (`/__castle/ws` -> `ws://localhost:${port}`) and node-side CLI clients that dial
827
- // `ws://localhost:${port}`. Binding 0.0.0.0 also exposed this control channel to
828
- // co-tenant containers across the shared Docker bridge.
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.
829
922
  const wss = new WebSocketServer({
830
- port,
831
- host: '127.0.0.1',
923
+ noServer: true,
832
924
  maxPayload: 12 * 1024 * 1024,
833
- verifyClient: ({ req }, done) => {
834
- // Node-side CLI clients are loopback and carry no browser Origin. Browser clients
835
- // arrive through Vite's loopback proxy but must prove both origin and a one-use ticket.
836
- if (!req.headers.origin) {
837
- done(req.socket.remoteAddress === '127.0.0.1' || req.socket.remoteAddress === '::1');
838
- return;
839
- }
840
- done(isSameOriginUpgrade(req) && security.consumeTicket(req, 'serve'));
841
- },
842
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
+ };
843
944
  const clients = new Set();
844
945
  const broadcast = (msg) => {
845
946
  const data = JSON.stringify(msg);
@@ -859,8 +960,9 @@ function startWSServer(port, projectDir, logFile, screenshotsDir, viteHolder, se
859
960
  clearTimeout(pending.timeout);
860
961
  requestOrigins.delete(requestId);
861
962
  };
862
- wss.on('connection', (ws) => {
963
+ wss.on('connection', (ws, req) => {
863
964
  clients.add(ws);
965
+ const multiplayerUrl = devMultiplayerUrl(req);
864
966
  ws.on('message', (raw) => {
865
967
  try {
866
968
  const text = Array.isArray(raw)
@@ -870,12 +972,14 @@ function startWSServer(port, projectDir, logFile, screenshotsDir, viteHolder, se
870
972
  : Buffer.from(raw).toString('utf8');
871
973
  let msg = JSON.parse(text);
872
974
  let bridgeRole = null;
975
+ let bridgeContentOrigin = null;
873
976
  if (msg.type === 'deck_bridge') {
874
977
  if ((msg.role !== 'edit' && msg.role !== 'play') ||
875
978
  !msg.message ||
876
979
  typeof msg.message !== 'object')
877
980
  return;
878
981
  bridgeRole = msg.role;
982
+ bridgeContentOrigin = trustedBridgeContentOrigin(security, req, bridgeRole, msg.contentOrigin);
879
983
  msg = msg.message;
880
984
  const allowed = new Set(['log', 'screenshot_response', 'write_file', 'castle_command']);
881
985
  if (!allowed.has(String(msg.type)))
@@ -1005,7 +1109,11 @@ function startWSServer(port, projectDir, logFile, screenshotsDir, viteHolder, se
1005
1109
  // token, then replies to just this socket. See castle-web-sdk's
1006
1110
  // transport.ts (local channel) + host.ts.
1007
1111
  if (msg.type === 'castle_command' && typeof msg.requestId === 'string') {
1008
- void handleCastleCommand(ws, projectDir, broadcast, msg.requestId, msg.command, msg.params);
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);
1009
1117
  }
1010
1118
  }
1011
1119
  catch {
@@ -1021,7 +1129,34 @@ function startWSServer(port, projectDir, logFile, screenshotsDir, viteHolder, se
1021
1129
  }
1022
1130
  });
1023
1131
  });
1024
- 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;
1025
1160
  }
1026
1161
  function writeProjectFile(projectDir, requestedPath, contents) {
1027
1162
  if (typeof requestedPath !== 'string' || requestedPath.trim() === '') {
@@ -2,6 +2,8 @@ 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";
5
7
  export declare const MOBILE_HOST_PROTOCOL = "2";
6
8
  export declare function mintContentGrantLabel(grant: {
7
9
  role: ContentRole;
@@ -12,14 +14,16 @@ export declare function mintContentGrantLabel(grant: {
12
14
  }, signingKey: string): string;
13
15
  export declare class ServeSecurity {
14
16
  private readonly publicPort;
15
- private readonly localContentPorts;
16
17
  readonly serveToken: string;
17
18
  private readonly contentProxyToken;
18
19
  private readonly signingKey;
19
20
  private readonly serveNonce;
20
21
  private readonly tickets;
22
+ private localContentPorts;
21
23
  constructor(publicPort: number, localContentPorts?: LocalContentPorts);
24
+ setLocalContentPorts(ports: LocalContentPorts): void;
22
25
  authorizeHttp(req: http.IncomingMessage): boolean;
26
+ rejectHttpAuth(res: http.ServerResponse): void;
23
27
  issueTicket(endpoint: SocketEndpoint): string;
24
28
  consumeTicket(req: http.IncomingMessage, endpoint: SocketEndpoint): boolean;
25
29
  private pruneTickets;