castle-web-cli 0.4.144 → 0.4.146

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 (40) hide show
  1. package/dist/imports.js +18 -3
  2. package/dist/init.js +1 -1
  3. package/dist/serve.d.ts +2 -0
  4. package/dist/serve.js +130 -10
  5. package/dist/serveSecurity.d.ts +5 -1
  6. package/dist/serveSecurity.js +27 -8
  7. package/dist/shell/assets/{index-qbygvQIx.js → index-CL9TuLXb.js} +86 -86
  8. package/dist/shell/assets/index-DN8HQBnW.css +1 -0
  9. package/dist/shell/index.html +2 -2
  10. package/kits/physics-2d/CLAUDE.md +44 -0
  11. package/kits/physics-2d/behaviors/Collider.jsx +21 -0
  12. package/kits/physics-2d/behaviors/Draggable.jsx +9 -0
  13. package/kits/physics-2d/behaviors/Layout.jsx +7 -0
  14. package/kits/physics-2d/behaviors/RigidBody.jsx +6 -0
  15. package/kits/physics-2d/behaviors/Sprite.jsx +7 -0
  16. package/kits/physics-2d/castle.json +1 -1
  17. package/kits/physics-2d/editors/BlueprintLibrary.jsx +64 -32
  18. package/kits/physics-2d/editors/NewBlueprintModal.jsx +69 -0
  19. package/kits/physics-2d/editors/PlayOnly.jsx +1 -1
  20. package/kits/physics-2d/editors/SceneEditor.jsx +333 -108
  21. package/kits/physics-2d/editors/SelectionOverlay.jsx +6 -2
  22. package/kits/physics-2d/editors/SingleEditor.jsx +6 -1
  23. package/kits/physics-2d/editors/behaviorRegistry.js +78 -5
  24. package/kits/physics-2d/engine/SceneUI.jsx +2 -2
  25. package/kits/physics-2d/engine/blueprint.js +212 -15
  26. package/kits/physics-2d/engine/editorFlags.js +50 -0
  27. package/kits/physics-2d/engine/files.js +9 -0
  28. package/kits/physics-2d/engine/liveReload.js +16 -4
  29. package/kits/physics-2d/engine/panelPrefs.js +78 -0
  30. package/kits/physics-2d/engine/panelSorting.jsx +84 -0
  31. package/kits/physics-2d/engine/physics/PhysicsSystem.js +5 -2
  32. package/kits/physics-2d/engine/physics/matterBridge.js +12 -2
  33. package/kits/physics-2d/engine/scene.js +94 -3
  34. package/kits/physics-2d/engine/ui.jsx +157 -4
  35. package/kits/physics-2d/engine/ui.module.css +615 -1
  36. package/kits/physics-2d/package-lock.json +78 -1
  37. package/kits/physics-2d/package.json +4 -0
  38. package/kits/physics-3d/castle.json +1 -1
  39. package/package.json +1 -1
  40. package/dist/shell/assets/index-CcVJjnL3.css +0 -1
package/dist/imports.js CHANGED
@@ -186,6 +186,19 @@ function unlockImportTree(dir) {
186
186
  // leaves its packages behind -- harmless (an unused package), and the honest
187
187
  // alternative needs provenance we don't track yet: once a deck starts importing
188
188
  // a package directly, "who added it" is no longer answerable from package.json.
189
+ // Never fatal: a deck whose install failed is still a deck whose files updated,
190
+ // so name the recovery command rather than aborting the serve.
191
+ async function installAddedDependencies(deckDir, added) {
192
+ if (added.length === 0)
193
+ return;
194
+ try {
195
+ const { installDeps } = await import('./install.js');
196
+ await installDeps(deckDir, false);
197
+ }
198
+ catch (e) {
199
+ console.warn(`Added ${added.length === 1 ? 'a dependency' : `${added.length} dependencies`} but installing failed -- run \`castle-web install\`. ${e instanceof Error ? e.message : String(e)}`);
200
+ }
201
+ }
189
202
  export function syncImportDependencies(deckDir) {
190
203
  const deckPkgPath = path.join(deckDir, 'package.json');
191
204
  let deckPkg;
@@ -705,9 +718,10 @@ export async function autoUpdateImports(deckDir) {
705
718
  }
706
719
  }
707
720
  if (updated.length > 0) {
708
- for (const dep of syncImportDependencies(deckDir)) {
721
+ const added = syncImportDependencies(deckDir);
722
+ for (const dep of added)
709
723
  console.log(`auto-update: added dependency ${dep}`);
710
- }
724
+ await installAddedDependencies(deckDir, added);
711
725
  }
712
726
  return updated;
713
727
  }
@@ -734,7 +748,7 @@ export async function updateImport(dir, options = {}) {
734
748
  if (options.revert) {
735
749
  for (const alias of aliases)
736
750
  revertImport(deckDir, alias);
737
- syncImportDependencies(deckDir);
751
+ await installAddedDependencies(deckDir, syncImportDependencies(deckDir));
738
752
  writePlatformDocs(deckDir);
739
753
  return;
740
754
  }
@@ -773,6 +787,7 @@ export async function updateImport(dir, options = {}) {
773
787
  const added = syncImportDependencies(deckDir);
774
788
  for (const dep of added)
775
789
  console.log(`Added dependency ${dep}`);
790
+ await installAddedDependencies(deckDir, added);
776
791
  writePlatformDocs(deckDir);
777
792
  console.log('Play the deck to check the update before saving; `--revert` puts the old version back.');
778
793
  }
package/dist/init.js CHANGED
@@ -46,7 +46,7 @@ export const BARE_DOCS_KIT = 'blank';
46
46
  // Registry version of castle-web-sdk to inject when scaffolding from a
47
47
  // globally-installed castle-web (not from inside the workspace). Bumped
48
48
  // alongside cli/sdk version bumps.
49
- const PUBLISHED_SDK_VERSION = '0.4.17';
49
+ const PUBLISHED_SDK_VERSION = '0.4.18';
50
50
  // The account the first-party kits are (to be) published under, so a kit
51
51
  // imported from the CLI's copy is named the same as one fetched from the server.
52
52
  const KIT_AUTHOR = 'castle';
package/dist/serve.d.ts CHANGED
@@ -1,4 +1,6 @@
1
+ import * as http from 'http';
1
2
  export declare function appendCapped(file: string, line: string): void;
3
+ export declare function isViteClientUpgrade(req: http.IncomingMessage): boolean;
2
4
  export declare function isAllowedShellHost(hostHeader: string | undefined, configuredHost?: string): boolean;
3
5
  export declare function isAllowedContentFilesRequest(role: 'edit' | 'play' | null, method: string | undefined, reqPath: string): boolean;
4
6
  export declare function serve(dir: string, options?: {
package/dist/serve.js CHANGED
@@ -1,8 +1,9 @@
1
1
  import * as fs from 'fs';
2
+ import * as http from 'http';
2
3
  import * as net from 'net';
3
4
  import * as path from 'path';
4
5
  import { spawn } from 'child_process';
5
- import { createServer, } from 'vite';
6
+ import { createServer as createViteServer, } from 'vite';
6
7
  import { WebSocketServer, WebSocket } from 'ws';
7
8
  import { isIP } from 'net';
8
9
  import { createIdeServer, FAVICON_FILES, FAVICON_LINK_TAGS } from './ide.js';
@@ -16,7 +17,7 @@ import { FORKS_DIR, ownForkFile, splitImportRel } from './forks.js';
16
17
  import * as config from './config.js';
17
18
  import { graphql as castleGraphql } from './api.js';
18
19
  import { executeCommand } from './castle-host/host.js';
19
- import { ServeSecurity } from './serveSecurity.js';
20
+ import { ServeSecurity, } from './serveSecurity.js';
20
21
  import { isSameOriginUpgrade } from './wsOrigin.js';
21
22
  // The log is a tail, not an archive: append, and once it passes the cap drop
22
23
  // whole lines off the front until it is back under.
@@ -53,6 +54,110 @@ async function findFreePorts(startPort) {
53
54
  }
54
55
  throw new Error(`No free port pair found starting from ${startPort}`);
55
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);
62
+ }
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] };
66
+ }
67
+ function listenLocalContentServer(upstreamHost, upstreamPort, port, role, security) {
68
+ const upstreamHeaders = (req) => ({
69
+ ...req.headers,
70
+ ...security.localContentProxyHeaders(role),
71
+ host: `localhost:${upstreamPort}`,
72
+ });
73
+ const server = http.createServer((req, res) => {
74
+ const upstream = http.request({
75
+ hostname: upstreamHost,
76
+ port: upstreamPort,
77
+ method: req.method,
78
+ path: req.url,
79
+ headers: upstreamHeaders(req),
80
+ }, (upstreamRes) => {
81
+ res.writeHead(upstreamRes.statusCode || 502, upstreamRes.headers);
82
+ upstreamRes.pipe(res);
83
+ });
84
+ upstream.on('error', () => {
85
+ if (!res.headersSent)
86
+ res.writeHead(502);
87
+ res.end('local content upstream unavailable');
88
+ });
89
+ req.pipe(upstream);
90
+ });
91
+ server.on('upgrade', (req, socket, head) => {
92
+ if (!isViteClientUpgrade(req)) {
93
+ socket.destroy();
94
+ return;
95
+ }
96
+ proxyViteClientUpgrade(req, socket, head, upstreamHost, upstreamPort, upstreamHeaders(req));
97
+ });
98
+ return new Promise((resolve, reject) => {
99
+ server.once('error', reject);
100
+ server.listen(port, '127.0.0.1', () => {
101
+ server.off('error', reject);
102
+ resolve(server);
103
+ });
104
+ });
105
+ }
106
+ function proxyViteClientUpgrade(req, socket, head, upstreamHost, upstreamPort, headers) {
107
+ const upstream = http.request({
108
+ hostname: upstreamHost,
109
+ port: upstreamPort,
110
+ method: req.method,
111
+ path: req.url,
112
+ headers,
113
+ });
114
+ upstream.on('upgrade', (response, upstreamSocket, upstreamHead) => {
115
+ const responseHeaders = [];
116
+ for (let i = 0; i < response.rawHeaders.length; i += 2) {
117
+ responseHeaders.push(`${response.rawHeaders[i]}: ${response.rawHeaders[i + 1]}`);
118
+ }
119
+ socket.write(`HTTP/1.1 ${response.statusCode || 101} ${response.statusMessage || 'Switching Protocols'}\r\n${responseHeaders.join('\r\n')}\r\n\r\n`);
120
+ if (upstreamHead.length)
121
+ socket.write(upstreamHead);
122
+ if (head.length)
123
+ upstreamSocket.write(head);
124
+ socket.pipe(upstreamSocket).pipe(socket);
125
+ });
126
+ upstream.on('response', (response) => {
127
+ socket.write(`HTTP/1.1 ${response.statusCode || 502} ${response.statusMessage || ''}\r\n\r\n`);
128
+ response.pipe(socket);
129
+ });
130
+ upstream.on('error', () => socket.destroy());
131
+ upstream.end();
132
+ }
133
+ export function isViteClientUpgrade(req) {
134
+ const protocol = req.headers['sec-websocket-protocol'];
135
+ if (protocol !== 'vite-hmr' && protocol !== 'vite-ping')
136
+ return false;
137
+ try {
138
+ return new URL(req.url || '/', 'http://localhost').pathname === '/';
139
+ }
140
+ catch {
141
+ return false;
142
+ }
143
+ }
144
+ async function startLocalContentServers(upstreamHost, upstreamPort, ports, security) {
145
+ const servers = [];
146
+ 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));
152
+ }
153
+ return servers;
154
+ }
155
+ catch (error) {
156
+ for (const server of servers)
157
+ server.close();
158
+ throw error;
159
+ }
160
+ }
56
161
  // Injected into the deck iframe (only when it carries `?logs=1`, i.e. the
57
162
  // editor's builtin Play panel) to forward the deck's console output to the
58
163
  // shell via postMessage, where the builtin Play panel renders a logs drawer.
@@ -404,7 +509,8 @@ export async function serve(dir, options = {}) {
404
509
  const { port, wsPort } = options.port
405
510
  ? { port: startPort, wsPort: startPort + 1 }
406
511
  : await findFreePorts(startPort);
407
- const security = new ServeSecurity(port);
512
+ const localContentPorts = await findLocalContentPorts(port + 2, new Set([port, wsPort]));
513
+ const security = new ServeSecurity(port, localContentPorts);
408
514
  // Local WebSocket server for SDK communication
409
515
  const castleDir = path.join(projectDir, '.castle');
410
516
  if (!fs.existsSync(castleDir))
@@ -424,12 +530,6 @@ export async function serve(dir, options = {}) {
424
530
  const logFile = path.join(castleDir, 'logs.txt');
425
531
  const screenshotsDir = path.join(castleDir, 'screenshots');
426
532
  const serveJsonPath = path.join(castleDir, 'serve.json');
427
- fs.writeFileSync(serveJsonPath, JSON.stringify({
428
- port,
429
- wsPort,
430
- pid: process.pid,
431
- contentPlayUrl: security.localContentOrigin('play'),
432
- }) + '\n');
433
533
  process.on('exit', () => {
434
534
  try {
435
535
  fs.unlinkSync(serveJsonPath);
@@ -489,7 +589,7 @@ export async function serve(dir, options = {}) {
489
589
  authorizeUpgrade: (req) => security.consumeTicket(req, 'agent'),
490
590
  });
491
591
  process.on('exit', () => agentServer.shutdown());
492
- const vite = await createServer({
592
+ const vite = await createViteServer({
493
593
  root: projectDir,
494
594
  plugins: [
495
595
  castlePlugin(security, ideServer, agentServer, options.host),
@@ -530,7 +630,27 @@ export async function serve(dir, options = {}) {
530
630
  invalidate: (paths) => invalidateModuleCaches(vite, paths),
531
631
  log: (line) => appendCapped(logFile, line),
532
632
  });
633
+ // Bring content up first so `--open` cannot race an iframe against a port
634
+ // that is not listening yet. Vite opens the shell from inside `vite.listen()`.
635
+ const upstreamHost = !options.host || options.host === 'localhost'
636
+ ? 'localhost'
637
+ : options.host === '0.0.0.0'
638
+ ? '127.0.0.1'
639
+ : options.host === '::'
640
+ ? '::1'
641
+ : options.host;
642
+ const localContentServers = await startLocalContentServers(upstreamHost, port, localContentPorts, security);
643
+ process.on('exit', () => {
644
+ for (const server of localContentServers)
645
+ server.close();
646
+ });
533
647
  await vite.listen();
648
+ fs.writeFileSync(serveJsonPath, JSON.stringify({
649
+ port,
650
+ wsPort,
651
+ pid: process.pid,
652
+ contentPlayUrl: security.localContentOrigin('play'),
653
+ }) + '\n');
534
654
  // The PTY WebSocket upgrade is handled directly on Vite's HTTP server rather
535
655
  // than through Vite's proxy (Vite's ws proxy didn't forward this path).
536
656
  if (vite.httpServer) {
@@ -1,6 +1,7 @@
1
1
  import type * as http from 'http';
2
2
  export type ContentRole = 'edit' | 'play';
3
3
  export type SocketEndpoint = 'serve' | 'pty' | 'agent';
4
+ export type LocalContentPorts = Record<ContentRole, number>;
4
5
  export declare function mintContentGrantLabel(grant: {
5
6
  role: ContentRole;
6
7
  publicPort: number;
@@ -10,11 +11,13 @@ export declare function mintContentGrantLabel(grant: {
10
11
  }, signingKey: string): string;
11
12
  export declare class ServeSecurity {
12
13
  private readonly publicPort;
14
+ private readonly localContentPorts;
13
15
  readonly serveToken: string;
16
+ private readonly contentProxyToken;
14
17
  private readonly signingKey;
15
18
  private readonly serveNonce;
16
19
  private readonly tickets;
17
- constructor(publicPort: number);
20
+ constructor(publicPort: number, localContentPorts?: LocalContentPorts);
18
21
  authorizeHttp(req: http.IncomingMessage): boolean;
19
22
  issueTicket(endpoint: SocketEndpoint): string;
20
23
  consumeTicket(req: http.IncomingMessage, endpoint: SocketEndpoint): boolean;
@@ -25,6 +28,7 @@ export declare class ServeSecurity {
25
28
  playOrigin: string;
26
29
  };
27
30
  localContentOrigin(role: ContentRole): string;
31
+ localContentProxyHeaders(role: ContentRole): Record<string, string>;
28
32
  verifyContentRequest(req: http.IncomingMessage): ContentRole | null;
29
33
  shellOrigin(req: http.IncomingMessage): string;
30
34
  private mintContentLabel;
@@ -49,12 +49,18 @@ export function mintContentGrantLabel(grant, signingKey) {
49
49
  }
50
50
  export class ServeSecurity {
51
51
  publicPort;
52
+ localContentPorts;
52
53
  serveToken = randomBytes(32).toString('base64url');
54
+ contentProxyToken = randomBytes(32).toString('base64url');
53
55
  signingKey = process.env.CASTLE_AGENT_TOKEN || randomBytes(32).toString('base64url');
54
56
  serveNonce = base32Lower(randomBytes(8));
55
57
  tickets = new Map();
56
- constructor(publicPort) {
58
+ constructor(publicPort, localContentPorts = {
59
+ edit: publicPort + 2,
60
+ play: publicPort + 3,
61
+ }) {
57
62
  this.publicPort = publicPort;
63
+ this.localContentPorts = localContentPorts;
58
64
  }
59
65
  authorizeHttp(req) {
60
66
  const value = req.headers['x-castle-serve-token'];
@@ -138,24 +144,37 @@ window.fetch=function(input,init){
138
144
  ? 'sandboxes-staging.castlexyz.com'
139
145
  : cloud
140
146
  ? 'sandboxes.castlexyz.com'
141
- : 'localhost';
147
+ : null;
142
148
  // Leave room for small positive clock skew at the control plane. Ghost still
143
149
  // enforces the hard 12-hour maximum when it resolves the capability.
144
150
  const expiresAtSeconds = Math.floor(Date.now() / 1000) + MAX_GRANT_SECONDS - GRANT_CLOCK_SKEW_SECONDS;
145
151
  const originFor = (role) => {
152
+ // Safari on macOS 15 asks DNS to resolve `*.localhost`, where it fails.
153
+ // Dedicated loopback ports are still distinct browser origins and need no DNS.
154
+ if (!cloud || !contentDomain)
155
+ return this.localContentOrigin(role);
146
156
  const label = this.mintContentLabel(role, sandboxId, expiresAtSeconds);
147
- return cloud
148
- ? `https://${label}.${contentDomain}`
149
- : `${requestOrigin(req).split('://')[0]}://${label}.localhost:${this.publicPort}`;
157
+ return `https://${label}.${contentDomain}`;
150
158
  };
151
159
  return { editOrigin: originFor('edit'), playOrigin: originFor('play') };
152
160
  }
153
161
  localContentOrigin(role) {
154
- const expiresAtSeconds = Math.floor(Date.now() / 1000) + MAX_GRANT_SECONDS - GRANT_CLOCK_SKEW_SECONDS;
155
- const label = this.mintContentLabel(role, 'localdev000000', expiresAtSeconds);
156
- return `http://${label}.localhost:${this.publicPort}`;
162
+ return `http://127.0.0.1:${this.localContentPorts[role]}`;
163
+ }
164
+ localContentProxyHeaders(role) {
165
+ return {
166
+ 'x-castle-content-role': role,
167
+ 'x-castle-content-proxy-token': this.contentProxyToken,
168
+ };
157
169
  }
158
170
  verifyContentRequest(req) {
171
+ const proxyRole = req.headers['x-castle-content-role'];
172
+ const proxyToken = req.headers['x-castle-content-proxy-token'];
173
+ if ((proxyRole === 'edit' || proxyRole === 'play') &&
174
+ typeof proxyToken === 'string' &&
175
+ safeEqual(proxyToken, this.contentProxyToken)) {
176
+ return proxyRole;
177
+ }
159
178
  const host = hostWithoutPort(req.headers.host || '');
160
179
  const label = host.split('.')[0];
161
180
  const match = CONTENT_LABEL_RE.exec(label);