castle-web-cli 0.4.149 → 0.4.151

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 (49) hide show
  1. package/dist/agent.d.ts +1 -0
  2. package/dist/agent.js +12 -4
  3. package/dist/api.d.ts +45 -1
  4. package/dist/api.js +34 -2
  5. package/dist/castle-host/host.d.ts +17 -0
  6. package/dist/castle-host/host.js +10 -7
  7. package/dist/castleJson.d.ts +15 -0
  8. package/dist/castleJson.js +36 -0
  9. package/dist/devSessionChild.d.ts +1 -0
  10. package/dist/devSessionChild.js +129 -0
  11. package/dist/devSessionServer.d.ts +19 -0
  12. package/dist/devSessionServer.js +511 -0
  13. package/dist/headlessCover.js +28 -0
  14. package/dist/index.js +8 -8
  15. package/dist/init.js +9 -1
  16. package/dist/list-decks.js +7 -6
  17. package/dist/native/playtest-remote.d.ts +3 -0
  18. package/dist/native/playtest-remote.js +113 -0
  19. package/dist/preview.d.ts +1 -1
  20. package/dist/preview.js +4 -2
  21. package/dist/save-deck.js +82 -16
  22. package/dist/serve.js +245 -88
  23. package/dist/serveSecurity.d.ts +7 -1
  24. package/dist/serveSecurity.js +61 -10
  25. package/dist/serverBundle.d.ts +8 -0
  26. package/dist/serverBundle.js +82 -0
  27. package/dist/shell/assets/{index-BzFzFtEP.js → index-Dlhc3eZW.js} +42 -42
  28. package/dist/shell/assets/index-DwezawBs.css +1 -0
  29. package/dist/shell/index.html +2 -2
  30. package/kits/blank/.castle/agent/children.json +1 -0
  31. package/kits/blank/.castle/agent/messages.json +9 -0
  32. package/kits/blank/.castle/agent/pending-sends.json +1 -0
  33. package/kits/blank/.castle/agent/tasks/index.md +2 -0
  34. package/kits/blank/.castle/docs/platform.md +36 -0
  35. package/kits/blank/castle.json +5 -2
  36. package/kits/blank/node_modules/.vite/deps/_metadata.json +8 -0
  37. package/kits/blank/node_modules/.vite/deps/package.json +3 -0
  38. package/kits/physics-2d/behaviors/Collider.jsx +1 -2
  39. package/kits/physics-2d/behaviors/Joints.jsx +1 -1
  40. package/kits/physics-2d/castle.json +1 -1
  41. package/kits/physics-2d/editors/BlueprintLibrary.jsx +33 -3
  42. package/kits/physics-2d/editors/SceneEditor.jsx +171 -57
  43. package/kits/physics-2d/editors/SingleEditor.jsx +6 -0
  44. package/kits/physics-2d/engine/blueprint.js +106 -14
  45. package/kits/physics-2d/engine/scene.js +9 -2
  46. package/kits/physics-2d/engine/ui.jsx +30 -2
  47. package/kits/physics-2d/engine/ui.module.css +59 -0
  48. package/package.json +1 -1
  49. package/dist/shell/assets/index-DN8HQBnW.css +0 -1
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) {
@@ -276,11 +299,32 @@ window.__castleShellOrigin=(function(){
276
299
  res.writeHead(403).end('untrusted host');
277
300
  return;
278
301
  }
302
+ if (reqPath === '/__castle/browser-content-grant') {
303
+ if (content || req.method !== 'GET') {
304
+ res.writeHead(403).end();
305
+ return;
306
+ }
307
+ const url = security.browserContentOrigin('play');
308
+ if (!url) {
309
+ res.writeHead(404).end();
310
+ return;
311
+ }
312
+ res.writeHead(200, {
313
+ 'content-type': 'application/json',
314
+ 'cache-control': 'no-store',
315
+ });
316
+ res.end(JSON.stringify({ url }));
317
+ return;
318
+ }
279
319
  if (reqPath === '/__castle/ws-ticket') {
280
- if (content || req.method !== 'POST' || !security.authorizeHttp(req)) {
320
+ if (content || req.method !== 'POST') {
281
321
  res.writeHead(403).end();
282
322
  return;
283
323
  }
324
+ if (!security.authorizeHttp(req)) {
325
+ security.rejectHttpAuth(res);
326
+ return;
327
+ }
284
328
  const endpoint = new URL(req.url || '/', 'http://localhost').searchParams.get('endpoint');
285
329
  if (endpoint !== 'serve' && endpoint !== 'pty' && endpoint !== 'agent') {
286
330
  res.writeHead(400).end('invalid endpoint');
@@ -316,7 +360,7 @@ window.__castleShellOrigin=(function(){
316
360
  reqPath.startsWith('/__castle/ide/') ||
317
361
  FAVICON_FILES.some((name) => reqPath === `/${name}`);
318
362
  if (reqPath.startsWith('/__castle/') && !publicShellPath && !security.authorizeHttp(req)) {
319
- res.writeHead(403).end();
363
+ security.rejectHttpAuth(res);
320
364
  return;
321
365
  }
322
366
  // The split-view shell (`/`) + its static assets are served outside
@@ -363,7 +407,7 @@ async function devHostContext(projectDir) {
363
407
  username: me.username,
364
408
  };
365
409
  }
366
- async function handleCastleCommand(ws, projectDir, broadcast, requestId, command, params) {
410
+ async function handleCastleCommand(ws, projectDir, broadcast, multiplayer, multiplayerUrl, requestId, command, params) {
367
411
  const ctx = await devHostContext(projectDir);
368
412
  // The dev server services data commands via GraphQL but supplies no
369
413
  // platformHandler, so platform/capability commands (e.g. passes.purchase)
@@ -373,11 +417,50 @@ async function handleCastleCommand(ws, projectDir, broadcast, requestId, command
373
417
  const result = await executeCommand(ctx, command, params, {
374
418
  graphqlFetch: castleGraphql,
375
419
  showLeaderboard: (payload) => broadcast({ type: 'castle_leaderboard_show', payload }),
420
+ getMultiplayerSession: () => {
421
+ if (!multiplayer || !multiplayerUrl) {
422
+ return Promise.resolve({
423
+ status: 'unavailable',
424
+ url: null,
425
+ nonce: null,
426
+ sessionId: null,
427
+ });
428
+ }
429
+ return Promise.resolve({
430
+ status: 'ok',
431
+ url: multiplayerUrl,
432
+ nonce: multiplayer.mintNonce(devMultiplayerIdentity(ctx)),
433
+ sessionId: multiplayer.sessionId,
434
+ });
435
+ },
376
436
  });
377
437
  if (ws.readyState === WebSocket.OPEN) {
378
438
  ws.send(JSON.stringify({ type: 'castle_command_response', castleSdk: 1, requestId, ...result }));
379
439
  }
380
440
  }
441
+ function devMultiplayerIdentity(ctx) {
442
+ return {
443
+ userId: ctx.userId ?? 'dev-user',
444
+ username: ctx.username ?? 'Developer',
445
+ isAnonymous: ctx.userId === null,
446
+ };
447
+ }
448
+ function devMultiplayerUrl(req) {
449
+ const base = typeof req.headers.origin === 'string' ? req.headers.origin : null;
450
+ if (!base)
451
+ return null;
452
+ return devMultiplayerUrlFromOrigin(base);
453
+ }
454
+ function devMultiplayerUrlFromOrigin(base) {
455
+ try {
456
+ const url = new URL('/__castle/mp', base);
457
+ url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:';
458
+ return url.toString();
459
+ }
460
+ catch {
461
+ return null;
462
+ }
463
+ }
381
464
  function readDeckContext(projectDir) {
382
465
  try {
383
466
  const raw = fs.readFileSync(path.join(projectDir, 'castle.json'), 'utf8');
@@ -399,13 +482,12 @@ function readServeJson(projectDir) {
399
482
  try {
400
483
  const raw = fs.readFileSync(path.join(projectDir, '.castle', 'serve.json'), 'utf8');
401
484
  const info = JSON.parse(raw);
402
- if (typeof info.port !== 'number' ||
403
- typeof info.wsPort !== 'number' ||
404
- typeof info.pid !== 'number')
485
+ if (typeof info.port !== 'number' || typeof info.pid !== 'number')
405
486
  return null;
406
487
  return {
407
488
  port: info.port,
408
- wsPort: info.wsPort,
489
+ wsPort: typeof info.wsPort === 'number' ? info.wsPort : undefined,
490
+ wsPath: typeof info.wsPath === 'string' ? info.wsPath : undefined,
409
491
  pid: info.pid,
410
492
  contentPlayUrl: typeof info.contentPlayUrl === 'string' ? info.contentPlayUrl : undefined,
411
493
  };
@@ -516,9 +598,11 @@ export async function serve(dir, options = {}) {
516
598
  // playtest tool, so this is free when that already pulled it, and every
517
599
  // failure is swallowed -- the capture re-detects and reports properly at the
518
600
  // point it actually matters.
519
- void import('./native/playtest-browser.js')
520
- .then((m) => m.createPlaytestBrowserManager().prewarm())
521
- .catch(() => undefined);
601
+ if (!process.env.CASTLE_SANDBOX_ID) {
602
+ void import('./native/playtest-browser.js')
603
+ .then((m) => m.createPlaytestBrowserManager().prewarm())
604
+ .catch(() => undefined);
605
+ }
522
606
  // Close stdin when not attached to a TTY so the process can be cleanly
523
607
  // backgrounded with `&` (otherwise stdin reads can block or hold the parent).
524
608
  if (!process.stdin.isTTY) {
@@ -530,11 +614,8 @@ export async function serve(dir, options = {}) {
530
614
  }
531
615
  }
532
616
  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);
617
+ const port = options.port ? startPort : await findFreePort(startPort);
618
+ const security = new ServeSecurity(port);
538
619
  // Local WebSocket server for SDK communication
539
620
  const castleDir = path.join(projectDir, '.castle');
540
621
  if (!fs.existsSync(castleDir))
@@ -567,10 +648,27 @@ export async function serve(dir, options = {}) {
567
648
  // Terminal close: exit through the handlers so child agent processes die
568
649
  // with the serve instead of orphaning.
569
650
  process.on('SIGHUP', () => process.exit());
651
+ let broadcastDevLog = () => undefined;
652
+ const devSession = resolveServerConfig(projectDir)
653
+ ? await startDevSessionServer({
654
+ projectDir,
655
+ log: (level, text) => {
656
+ const line = `[server] ${text}`;
657
+ appendCapped(logFile, `${line}\n`);
658
+ if (level === 'error')
659
+ process.stderr.write(`${line}\n`);
660
+ else
661
+ process.stdout.write(`${line}\n`);
662
+ broadcastDevLog({ type: 'server_log', level, text: line });
663
+ },
664
+ })
665
+ : null;
666
+ process.on('exit', () => devSession?.shutdownNow());
570
667
  // The WS server forwards `restart` to the browser, but it also needs the
571
668
  // Vite instance so it can drop transform caches first (see invalidateModuleCaches).
572
669
  const viteHolder = { vite: null };
573
- const { broadcast } = startWSServer(wsPort, projectDir, logFile, screenshotsDir, viteHolder, security);
670
+ const { broadcast, handleUpgrade: handleCastleUpgrade } = startWSServer(projectDir, logFile, screenshotsDir, viteHolder, security, devSession);
671
+ broadcastDevLog = broadcast;
574
672
  // The deck root `/` serves a split-view shell: the deck in an iframe plus a
575
673
  // toggle button for an xterm.js terminal. The terminal's PTY is lazy -- it
576
674
  // spawns only when a browser first opens the PTY WebSocket.
@@ -592,6 +690,18 @@ export async function serve(dir, options = {}) {
592
690
  authorizeUpgrade: (req) => security.consumeTicket(req, 'pty'),
593
691
  });
594
692
  process.on('exit', () => ideServer.shutdown());
693
+ const upstreamHost = !options.host || options.host === 'localhost'
694
+ ? 'localhost'
695
+ : options.host === '0.0.0.0'
696
+ ? '127.0.0.1'
697
+ : options.host === '::'
698
+ ? '::1'
699
+ : options.host;
700
+ const localContentServers = await startLocalContentServers(upstreamHost, port, security, new Set([port]));
701
+ process.on('exit', () => {
702
+ for (const server of localContentServers)
703
+ server.close();
704
+ });
595
705
  // The agent panel backend: router conversation + background task agents,
596
706
  // state under .castle/agent/. Its WebSocket shares Vite's HTTP server.
597
707
  const agentServer = createAgentServer({
@@ -599,6 +709,9 @@ export async function serve(dir, options = {}) {
599
709
  deckLabel: path.basename(projectDir),
600
710
  port,
601
711
  playtestServeUrl: security.localContentOrigin('play'),
712
+ browserContentUrl: process.env.CASTLE_SANDBOX_ID
713
+ ? () => security.browserContentOrigin('play')
714
+ : undefined,
602
715
  // Same effect as the WS server's own 'restart' branch below (invalidate
603
716
  // then tell every connected tab to reload), called directly in-process
604
717
  // instead of round-tripping through a WebSocket message -- this is what
@@ -631,10 +744,14 @@ export async function serve(dir, options = {}) {
631
744
  open: options.open ? true : undefined,
632
745
  hmr: false,
633
746
  proxy: {
634
- '/__castle/ws': {
635
- target: `ws://localhost:${wsPort}`,
636
- ws: true,
637
- },
747
+ ...(devSession
748
+ ? {
749
+ '/__castle/mp': {
750
+ target: `ws://127.0.0.1:${devSession.port}`,
751
+ ws: true,
752
+ },
753
+ }
754
+ : {}),
638
755
  },
639
756
  fs: {
640
757
  strict: true,
@@ -655,45 +772,43 @@ export async function serve(dir, options = {}) {
655
772
  logLevel: 'info',
656
773
  });
657
774
  viteHolder.vite = vite;
775
+ // Castle's control socket shares the public Vite listener. Keeping every
776
+ // externally-reachable deck endpoint on P means adjacent decks may safely
777
+ // use P+1; only Safari's loopback content proxies need extra listeners, and
778
+ // those are OS-assigned ephemeral ports.
779
+ if (vite.httpServer) {
780
+ vite.httpServer.on('upgrade', (req, socket, head) => {
781
+ if (handleCastleUpgrade(req, socket, head))
782
+ return;
783
+ if (!ideServer.handleUpgrade(req, socket, head)) {
784
+ agentServer.handleUpgrade(req, socket, head);
785
+ }
786
+ });
787
+ }
658
788
  // File changes from ANY source (editors, agents, terminal) become one
659
789
  // coalesced `files_changed` broadcast; consumers decide what to reload.
660
790
  installFilesChangedWatcher({
661
791
  vite,
662
792
  projectDir,
663
- broadcast,
793
+ broadcast: (message) => {
794
+ devSession?.handleFilesChanged(message);
795
+ broadcast(message);
796
+ },
664
797
  invalidate: (paths) => invalidateModuleCaches(vite, paths),
665
798
  log: (line) => appendCapped(logFile, line),
666
799
  });
667
800
  // Bring content up first so `--open` cannot race an iframe against a port
668
801
  // 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
802
  await vite.listen();
682
803
  fs.writeFileSync(serveJsonPath, JSON.stringify({
683
804
  port,
684
- wsPort,
805
+ // Kept for older CLI commands: they connect to this port's root path.
806
+ // New clients use wsPath. Both routes reach the same noServer WSS.
807
+ wsPort: port,
808
+ wsPath: '/__castle/ws',
685
809
  pid: process.pid,
686
810
  contentPlayUrl: security.localContentOrigin('play'),
687
811
  }) + '\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
812
  vite.printUrls();
698
813
  }
699
814
  // `restart` does a full browser reload, but Vite keeps transformed modules
@@ -821,25 +936,33 @@ async function serveDetached(projectDir, options) {
821
936
  }
822
937
  throw new Error(`Detached serve did not write ${serveJsonPath} within 15s; check ${logPath} for startup errors.`);
823
938
  }
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.
939
+ function startWSServer(projectDir, logFile, screenshotsDir, viteHolder, security, multiplayer) {
940
+ // The control socket is upgraded directly on Vite's HTTP server. Browser
941
+ // clients use the named path and a one-use ticket. The root path is accepted
942
+ // only from loopback clients with no Origin so older CLI versions can read
943
+ // wsPort from a new serve.json and continue to connect during rollout.
829
944
  const wss = new WebSocketServer({
830
- port,
831
- host: '127.0.0.1',
945
+ noServer: true,
832
946
  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
947
  });
948
+ const handleUpgrade = (req, socket, head) => {
949
+ const pathname = new URL(req.url || '/', 'http://localhost').pathname;
950
+ const hasOrigin = Boolean(req.headers.origin);
951
+ const isNamedPath = pathname === '/__castle/ws';
952
+ const isLegacyCliPath = pathname === '/' && !hasOrigin;
953
+ if (!isNamedPath && !isLegacyCliPath)
954
+ return false;
955
+ const loopback = req.socket.remoteAddress === '127.0.0.1' || req.socket.remoteAddress === '::1';
956
+ const authorized = hasOrigin
957
+ ? isNamedPath && isSameOriginUpgrade(req) && security.consumeTicket(req, 'serve')
958
+ : loopback;
959
+ if (!authorized) {
960
+ socket.destroy();
961
+ return true;
962
+ }
963
+ wss.handleUpgrade(req, socket, head, (ws) => wss.emit('connection', ws, req));
964
+ return true;
965
+ };
843
966
  const clients = new Set();
844
967
  const broadcast = (msg) => {
845
968
  const data = JSON.stringify(msg);
@@ -859,8 +982,9 @@ function startWSServer(port, projectDir, logFile, screenshotsDir, viteHolder, se
859
982
  clearTimeout(pending.timeout);
860
983
  requestOrigins.delete(requestId);
861
984
  };
862
- wss.on('connection', (ws) => {
985
+ wss.on('connection', (ws, req) => {
863
986
  clients.add(ws);
987
+ const multiplayerUrl = devMultiplayerUrl(req);
864
988
  ws.on('message', (raw) => {
865
989
  try {
866
990
  const text = Array.isArray(raw)
@@ -870,12 +994,14 @@ function startWSServer(port, projectDir, logFile, screenshotsDir, viteHolder, se
870
994
  : Buffer.from(raw).toString('utf8');
871
995
  let msg = JSON.parse(text);
872
996
  let bridgeRole = null;
997
+ let bridgeContentOrigin = null;
873
998
  if (msg.type === 'deck_bridge') {
874
999
  if ((msg.role !== 'edit' && msg.role !== 'play') ||
875
1000
  !msg.message ||
876
1001
  typeof msg.message !== 'object')
877
1002
  return;
878
1003
  bridgeRole = msg.role;
1004
+ bridgeContentOrigin = trustedBridgeContentOrigin(security, req, bridgeRole, msg.contentOrigin);
879
1005
  msg = msg.message;
880
1006
  const allowed = new Set(['log', 'screenshot_response', 'write_file', 'castle_command']);
881
1007
  if (!allowed.has(String(msg.type)))
@@ -1005,7 +1131,11 @@ function startWSServer(port, projectDir, logFile, screenshotsDir, viteHolder, se
1005
1131
  // token, then replies to just this socket. See castle-web-sdk's
1006
1132
  // transport.ts (local channel) + host.ts.
1007
1133
  if (msg.type === 'castle_command' && typeof msg.requestId === 'string') {
1008
- void handleCastleCommand(ws, projectDir, broadcast, msg.requestId, msg.command, msg.params);
1134
+ const commandMultiplayerUrl = bridgeRole
1135
+ ? devMultiplayerUrlFromOrigin(bridgeContentOrigin ??
1136
+ security.contentOrigins(req)[bridgeRole === 'edit' ? 'editOrigin' : 'playOrigin'])
1137
+ : multiplayerUrl;
1138
+ void handleCastleCommand(ws, projectDir, broadcast, multiplayer, commandMultiplayerUrl, msg.requestId, msg.command, msg.params);
1009
1139
  }
1010
1140
  }
1011
1141
  catch {
@@ -1021,7 +1151,34 @@ function startWSServer(port, projectDir, logFile, screenshotsDir, viteHolder, se
1021
1151
  }
1022
1152
  });
1023
1153
  });
1024
- return { wss, broadcast };
1154
+ return { wss, broadcast, handleUpgrade };
1155
+ }
1156
+ function normalizedHttpOrigin(value) {
1157
+ if (typeof value !== 'string')
1158
+ return null;
1159
+ try {
1160
+ const url = new URL(value);
1161
+ if (url.protocol !== 'http:' && url.protocol !== 'https:')
1162
+ return null;
1163
+ return url.origin;
1164
+ }
1165
+ catch {
1166
+ return null;
1167
+ }
1168
+ }
1169
+ function trustedBridgeContentOrigin(security, request, role, value) {
1170
+ const origin = normalizedHttpOrigin(value);
1171
+ if (!origin)
1172
+ return null;
1173
+ if (origin === security.localContentOrigin(role) || origin === request.headers.origin)
1174
+ return origin;
1175
+ const url = new URL(origin);
1176
+ const synthetic = {
1177
+ headers: { ...request.headers, host: url.host },
1178
+ socket: request.socket,
1179
+ url: role === 'play' ? '/index.html?edit=0' : '/index.html',
1180
+ };
1181
+ return security.verifyContentRequest(synthetic) === role ? origin : null;
1025
1182
  }
1026
1183
  function writeProjectFile(projectDir, requestedPath, contents) {
1027
1184
  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;
@@ -29,6 +33,8 @@ export declare class ServeSecurity {
29
33
  playOrigin: string;
30
34
  };
31
35
  localContentOrigin(role: ContentRole): string;
36
+ /** A short-lived play URL for one shared-browser admission attempt. */
37
+ browserContentOrigin(role?: ContentRole): string | null;
32
38
  localContentProxyHeaders(role: ContentRole): Record<string, string>;
33
39
  verifyContentRequest(req: http.IncomingMessage): ContentRole | null;
34
40
  compatibilityContentRole(req: http.IncomingMessage): ContentRole | null;