castle-web-cli 0.4.140 → 0.4.142

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/agent.d.ts CHANGED
@@ -77,6 +77,8 @@ export declare function createAgentServer(opts: {
77
77
  deckDir: string;
78
78
  deckLabel: string;
79
79
  port?: number;
80
+ playtestServeUrl?: string;
80
81
  restart?: () => void;
82
+ authorizeUpgrade?: (req: http.IncomingMessage, endpoint: 'agent') => boolean;
81
83
  }): AgentServer;
82
84
  export {};
package/dist/agent.js CHANGED
@@ -3853,14 +3853,26 @@ function foldRouterQueueTurn(ctx) {
3853
3853
  state.autoFoldUsed = true;
3854
3854
  broadcastQueueState(ctx);
3855
3855
  }
3856
- function handleQueueUserMessage(ctx, text, images) {
3856
+ // A client-supplied message id, or null if it isn't one we can safely adopt.
3857
+ // It becomes a message id AND an attachment directory name, so the character
3858
+ // set is the tight one -- nothing here may traverse a path.
3859
+ function safeClientMessageId(clientId) {
3860
+ if (typeof clientId !== 'string')
3861
+ return null;
3862
+ return /^[A-Za-z0-9_-]{1,32}$/.test(clientId) ? clientId : null;
3863
+ }
3864
+ function handleQueueUserMessage(ctx, text, images, clientId) {
3857
3865
  const { state } = ctx;
3858
3866
  // Mid-run: queue (don't interrupt). It shows as a queued row in the
3859
3867
  // composer and flushes when the current turn settles. Idle: start now.
3860
3868
  // Persist at enqueue (assign the final message id, save attachments to
3861
3869
  // disk, mirror the queue to pending-sends.json) so a restart before the
3862
3870
  // queue drains can recover the send instead of silently dropping it.
3863
- const id = nanoid(8);
3871
+ //
3872
+ // The id is the SENDER's when it supplied one: the client shows the message
3873
+ // the moment you hit send, and reusing that row's id means the echo lands on
3874
+ // the same row rather than beside it as a duplicate.
3875
+ const id = safeClientMessageId(clientId) ?? nanoid(8);
3864
3876
  const attachments = saveAttachments(ctx.attachmentsDir, id, images);
3865
3877
  state.pendingSends.push({ id, text, attachments });
3866
3878
  persistPendingSends(ctx);
@@ -3947,7 +3959,7 @@ function createRouterQueue(deps) {
3947
3959
  persistPendingSends(ctx);
3948
3960
  maybeStartRouterQueueTurn(ctx);
3949
3961
  return {
3950
- handleUserMessage: (text, images) => handleQueueUserMessage(ctx, text, images),
3962
+ handleUserMessage: (text, images, clientId) => handleQueueUserMessage(ctx, text, images, clientId),
3951
3963
  interruptRouter: () => interruptRouterQueue(ctx),
3952
3964
  cancelQueued: (index) => cancelQueuedSend(ctx, index),
3953
3965
  isRunning: () => ctx.state.routerRunning,
@@ -3983,7 +3995,7 @@ export function createAgentServer(opts) {
3983
3995
  // 127.0.0.1 never answers there, and playtest would fail every call
3984
3996
  // with a navigation error. `localhost` resolves correctly under
3985
3997
  // every binding mode (default ::1, --host 0.0.0.0, explicit IPs).
3986
- serveUrl: `http://localhost:${opts.port}`,
3998
+ serveUrl: opts.playtestServeUrl ?? `http://localhost:${opts.port}`,
3987
3999
  // Kicks off the one-time Chromium download in the background at
3988
4000
  // smith-task start (see runTaskAgentIn) -- single-flight with any
3989
4001
  // real playtest call, silent on every failure path.
@@ -4087,6 +4099,21 @@ export function createAgentServer(opts) {
4087
4099
  taskStore.acknowledge(id, rejected);
4088
4100
  }
4089
4101
  const wss = new WebSocketServer({ noServer: true });
4102
+ // Ids of user messages already accepted, so a client's resend after a lost
4103
+ // ack is dropped rather than asked twice. Bounded and insertion-ordered: a
4104
+ // resend follows within a reconnect or two, never thousands of messages
4105
+ // later, so the oldest entries are safe to forget.
4106
+ const seenClientIds = new Set();
4107
+ const MAX_SEEN_CLIENT_IDS = 500;
4108
+ function rememberClientId(clientId) {
4109
+ seenClientIds.add(clientId);
4110
+ while (seenClientIds.size > MAX_SEEN_CLIENT_IDS) {
4111
+ const oldest = seenClientIds.values().next().value;
4112
+ if (oldest === undefined)
4113
+ break;
4114
+ seenClientIds.delete(oldest);
4115
+ }
4116
+ }
4090
4117
  function attachClient(socket) {
4091
4118
  clients.add(socket);
4092
4119
  const hello = {
@@ -4123,7 +4150,21 @@ export function createAgentServer(opts) {
4123
4150
  const hasText = typeof msg.text === 'string' && msg.text.trim() !== '';
4124
4151
  const hasImages = Array.isArray(msg.images) && msg.images.length > 0;
4125
4152
  if (msg.type === 'user-message' && (hasText || hasImages)) {
4126
- routerQueue.handleUserMessage(typeof msg.text === 'string' ? msg.text.trim() : '', msg.images);
4153
+ // A client resends anything it never saw acknowledged -- an ack lost
4154
+ // with the socket must not cost the message. So the id is what makes a
4155
+ // resend idempotent: seen once, dropped after, always acknowledged.
4156
+ const clientId = safeClientMessageId(msg.clientId);
4157
+ const duplicate = clientId !== null && seenClientIds.has(clientId);
4158
+ if (!duplicate) {
4159
+ if (clientId !== null)
4160
+ rememberClientId(clientId);
4161
+ routerQueue.handleUserMessage(typeof msg.text === 'string' ? msg.text.trim() : '', msg.images, clientId ?? undefined);
4162
+ }
4163
+ if (clientId !== null) {
4164
+ if (socket.readyState === socket.OPEN) {
4165
+ socket.send(JSON.stringify({ type: 'user-message-ack', clientId }));
4166
+ }
4167
+ }
4127
4168
  }
4128
4169
  else if (msg.type === 'interrupt') {
4129
4170
  routerQueue.interruptRouter();
@@ -4174,7 +4215,7 @@ export function createAgentServer(opts) {
4174
4215
  // The agent socket drives the coding agent (exec, file writes) — reject any upgrade
4175
4216
  // that isn't same-origin (a co-tenant reaching this port directly sends no browser
4176
4217
  // Origin). Consumed either way so a rejected upgrade never falls through.
4177
- if (!isSameOriginUpgrade(req)) {
4218
+ if (!isSameOriginUpgrade(req) || (opts.authorizeUpgrade && !opts.authorizeUpgrade(req, 'agent'))) {
4178
4219
  socket.write('HTTP/1.1 403 Forbidden\r\n\r\n');
4179
4220
  socket.destroy();
4180
4221
  return true;
package/dist/ide.d.ts CHANGED
@@ -28,4 +28,6 @@ export declare function createIdeServer(opts: {
28
28
  * deck-relative paths whose resolution changed, not just their contents.
29
29
  */
30
30
  invalidate?: (paths?: string[]) => void;
31
+ shellBootstrap?: (req: http.IncomingMessage) => string;
32
+ authorizeUpgrade?: (req: http.IncomingMessage, endpoint: 'pty') => boolean;
31
33
  }): IdeServer;
package/dist/ide.js CHANGED
@@ -101,6 +101,22 @@ function serveShellFile(res, asset) {
101
101
  fs.createReadStream(filePath).pipe(res);
102
102
  return true;
103
103
  }
104
+ function serveShellIndex(req, res, bootstrap) {
105
+ const filePath = path.join(SHELL_DIR, 'index.html');
106
+ if (!fs.existsSync(filePath)) {
107
+ res.writeHead(404).end();
108
+ return true;
109
+ }
110
+ let html = fs.readFileSync(filePath, 'utf8');
111
+ if (bootstrap)
112
+ html = html.replace(/<head(\s[^>]*)?>/i, (head) => `${head}${bootstrap(req)}`);
113
+ res.writeHead(200, {
114
+ 'content-type': 'text/html; charset=utf-8',
115
+ 'cache-control': 'no-store',
116
+ });
117
+ res.end(html);
118
+ return true;
119
+ }
104
120
  // The split-view shell is served at the deck root `/` (the deck itself moves
105
121
  // into the iframe at `/index.html`); `/__castle/ide/<asset>` are the shell's
106
122
  // static assets; `/__castle/pty` is the PTY WebSocket (handled via a direct
@@ -1111,7 +1127,7 @@ export function createIdeServer(opts) {
1111
1127
  // The PTY is a root login shell — reject any upgrade that isn't same-origin (a
1112
1128
  // co-tenant reaching this port directly sends no browser Origin). Consumed either
1113
1129
  // way so a rejected upgrade never falls through to another handler.
1114
- if (!isSameOriginUpgrade(req)) {
1130
+ if (!isSameOriginUpgrade(req) || (opts.authorizeUpgrade && !opts.authorizeUpgrade(req, 'pty'))) {
1115
1131
  socket.write('HTTP/1.1 403 Forbidden\r\n\r\n');
1116
1132
  socket.destroy();
1117
1133
  return true;
@@ -1122,7 +1138,7 @@ export function createIdeServer(opts) {
1122
1138
  function handleHttpRequest(req, res, reqPath) {
1123
1139
  // `/` -> the shell's index.html; `/__castle/ide/<asset>` -> bundle assets.
1124
1140
  if (reqPath === '/')
1125
- return serveShellFile(res, 'index.html');
1141
+ return serveShellIndex(req, res, opts.shellBootstrap);
1126
1142
  // Root-served favicons, unless the deck ships its own (then fall through
1127
1143
  // to Vite, which serves the deck's file).
1128
1144
  const favicon = FAVICON_FILES.find((name) => reqPath === `/${name}`);
package/dist/init.js CHANGED
@@ -39,7 +39,7 @@ const DEFAULT_KIT = 'physics-2d';
39
39
  // Registry version of castle-web-sdk to inject when scaffolding from a
40
40
  // globally-installed castle-web (not from inside the workspace). Bumped
41
41
  // alongside cli/sdk version bumps.
42
- const PUBLISHED_SDK_VERSION = '0.4.15';
42
+ const PUBLISHED_SDK_VERSION = '0.4.17';
43
43
  // The account the first-party kits are (to be) published under, so a kit
44
44
  // imported from the CLI's copy is named the same as one fetched from the server.
45
45
  const KIT_AUTHOR = 'castle';
package/dist/save-deck.js CHANGED
@@ -93,7 +93,10 @@ async function uploadSource(projectDir, deckId) {
93
93
  function runningServeUrl(projectDir) {
94
94
  try {
95
95
  const raw = fs.readFileSync(path.join(projectDir, '.castle', 'serve.json'), 'utf8');
96
- const port = JSON.parse(raw).port;
96
+ const parsed = JSON.parse(raw);
97
+ if (typeof parsed.contentPlayUrl === 'string')
98
+ return parsed.contentPlayUrl;
99
+ const port = parsed.port;
97
100
  return typeof port === 'number' ? `http://localhost:${port}` : null;
98
101
  }
99
102
  catch {
package/dist/serve.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  export declare function appendCapped(file: string, line: string): void;
2
+ export declare function isAllowedShellHost(hostHeader: string | undefined, configuredHost?: string): boolean;
2
3
  export declare function serve(dir: string, options?: {
3
4
  port?: string;
4
5
  host?: string;
package/dist/serve.js CHANGED
@@ -4,7 +4,8 @@ import * as path from 'path';
4
4
  import { spawn } from 'child_process';
5
5
  import { createServer, } from 'vite';
6
6
  import { WebSocketServer, WebSocket } from 'ws';
7
- import { createIdeServer, FAVICON_LINK_TAGS } from './ide.js';
7
+ import { isIP } from 'net';
8
+ import { createIdeServer, FAVICON_FILES, FAVICON_LINK_TAGS } from './ide.js';
8
9
  import { createAgentServer } from './agent.js';
9
10
  import { sceneFilesPlugin, importsAliasPlugin, forksOverlayPlugin } from './vitePlugins.js';
10
11
  import { installFilesChangedWatcher } from './filesChanged.js';
@@ -13,6 +14,8 @@ import { FORKS_DIR, ownForkFile, splitImportRel } from './forks.js';
13
14
  import * as config from './config.js';
14
15
  import { graphql as castleGraphql } from './api.js';
15
16
  import { executeCommand } from './castle-host/host.js';
17
+ import { ServeSecurity } from './serveSecurity.js';
18
+ import { isSameOriginUpgrade } from './wsOrigin.js';
16
19
  // The log is a tail, not an archive: append, and once it passes the cap drop
17
20
  // whole lines off the front until it is back under.
18
21
  const LOG_MAX_BYTES = 2 * 1024 * 1024;
@@ -74,7 +77,30 @@ const CONSOLE_CAPTURE = `<script>(function(){
74
77
  };
75
78
  });
76
79
  })();</script>`;
77
- function castlePlugin(wsPort, ideServer, agentServer) {
80
+ function hostnameFromHeader(value) {
81
+ if (!value)
82
+ return '';
83
+ if (value.startsWith('[')) {
84
+ const end = value.indexOf(']');
85
+ return end > 0 ? value.slice(1, end).toLowerCase() : '';
86
+ }
87
+ return value.split(':')[0].toLowerCase();
88
+ }
89
+ export function isAllowedShellHost(hostHeader, configuredHost) {
90
+ const host = hostnameFromHeader(hostHeader);
91
+ if (!host)
92
+ return false;
93
+ if (host === 'localhost' || isIP(host) !== 0)
94
+ return true;
95
+ if (/^\d+-[a-z0-9]{14}\.sandboxes(?:-staging)?\.castle\.xyz$/.test(host))
96
+ return true;
97
+ // Preserve explicit LAN/tailnet development without accepting arbitrary DNS-rebinding hosts.
98
+ if (host.endsWith('.local') || host.endsWith('.ts.net'))
99
+ return true;
100
+ const configured = configuredHost ? hostnameFromHeader(configuredHost) : '';
101
+ return configured !== '' && configured !== '0.0.0.0' && configured !== '::' && host === configured;
102
+ }
103
+ function castlePlugin(security, ideServer, agentServer, configuredHost) {
78
104
  return {
79
105
  name: 'castle-dev',
80
106
  transformIndexHtml: {
@@ -88,37 +114,85 @@ function castlePlugin(wsPort, ideServer, agentServer) {
88
114
  const favicon = /<link[^>]+rel=["']?[^"'>]*icon/i.test(html)
89
115
  ? ''
90
116
  : `\n ${FAVICON_LINK_TAGS}`;
91
- return html.replace(/<head(\s[^>]*)?>/i, (match) => `${match}${favicon}\n <script>window.CastleEmbed={edit:true,host:'dev'};</script>\n ${CONSOLE_CAPTURE}`);
117
+ return html.replace(/<head(\s[^>]*)?>/i, (match) => `${match}${favicon}\n <script>
118
+ window.CastleEmbed={edit:true,host:'dev'};
119
+ window.__castleShellOrigin=(function(){
120
+ var h=location.hostname.toLowerCase(),m=/^1[ep]([0-9a-z]{1,4})-([a-z0-9]{14})-/.exec(h);
121
+ if(!m)return null;
122
+ var p=parseInt(m[1],36),sid=m[2];
123
+ if(h.endsWith('.sandboxes-staging.castlexyz.com'))return 'https://'+p+'-'+sid+'.sandboxes-staging.castle.xyz';
124
+ if(h.endsWith('.sandboxes.castlexyz.com'))return 'https://'+p+'-'+sid+'.sandboxes.castle.xyz';
125
+ return null;
126
+ })();
127
+ </script>\n ${CONSOLE_CAPTURE}`);
92
128
  },
93
129
  },
94
130
  configureServer(server) {
95
131
  server.middlewares.use((req, res, next) => {
96
- if (req.url === '/__castle/ws-port') {
97
- res.writeHead(200, { 'Content-Type': 'application/json' });
98
- res.end(JSON.stringify({ port: wsPort, path: '/__castle/ws' }));
132
+ const reqPath = (req.url || '/').split('?')[0];
133
+ const trustedSurface = req.headers['x-castle-sandbox-surface'];
134
+ const verifiedRole = security.verifyContentRequest(req);
135
+ const content = trustedSurface === 'content' || verifiedRole !== null;
136
+ if (content && !verifiedRole) {
137
+ res.writeHead(403).end('invalid content capability');
99
138
  return;
100
139
  }
101
- if (req.url === '/__castle/auth') {
102
- res.writeHead(200, { 'Content-Type': 'application/json' });
103
- res.end(JSON.stringify({ token: config.getToken(), userId: config.getUserId() }));
140
+ if (!content && !isAllowedShellHost(req.headers.host, configuredHost)) {
141
+ res.writeHead(403).end('untrusted host');
104
142
  return;
105
143
  }
106
- if (req.url === '/__castle/context') {
107
- res.writeHead(200, { 'Content-Type': 'application/json' });
108
- res.end(JSON.stringify(readDeckContext(server.config.root)));
144
+ if (reqPath === '/__castle/ws-ticket') {
145
+ if (content || req.method !== 'POST' || !security.authorizeHttp(req)) {
146
+ res.writeHead(403).end();
147
+ return;
148
+ }
149
+ const endpoint = new URL(req.url || '/', 'http://localhost').searchParams.get('endpoint');
150
+ if (endpoint !== 'serve' && endpoint !== 'pty' && endpoint !== 'agent') {
151
+ res.writeHead(400).end('invalid endpoint');
152
+ return;
153
+ }
154
+ res.writeHead(200, { 'content-type': 'application/json', 'cache-control': 'no-store' });
155
+ res.end(JSON.stringify({ ticket: security.issueTicket(endpoint) }));
156
+ return;
157
+ }
158
+ if (reqPath === '/__castle/auth' || reqPath === '/__castle/ws-port' || reqPath === '/__castle/context') {
159
+ res.writeHead(404).end();
160
+ return;
161
+ }
162
+ if (content) {
163
+ if (reqPath === '/')
164
+ req.url = `/index.html${req.url?.includes('?') ? req.url.slice(req.url.indexOf('?')) : ''}`;
165
+ const allowedRaw = verifiedRole === 'edit' && reqPath === '/__castle/files/raw';
166
+ const allowedVendor = reqPath.startsWith('/__castle/vendor/');
167
+ const allowedFavicon = FAVICON_FILES.some((name) => reqPath === `/${name}`);
168
+ if (reqPath.startsWith('/__castle/') && !allowedRaw && !allowedVendor) {
169
+ res.writeHead(403).end('content capability does not allow this endpoint');
170
+ return;
171
+ }
172
+ if ((allowedRaw || allowedVendor || allowedFavicon) && ideServer.handleHttpRequest(req, res, reqPath))
173
+ return;
174
+ next();
175
+ return;
176
+ }
177
+ const publicShellPath = reqPath === '/' ||
178
+ reqPath.startsWith('/__castle/ide/') ||
179
+ FAVICON_FILES.some((name) => reqPath === `/${name}`);
180
+ if (reqPath.startsWith('/__castle/') && !publicShellPath && !security.authorizeHttp(req)) {
181
+ res.writeHead(403).end();
109
182
  return;
110
183
  }
111
184
  // The split-view shell (`/`) + its static assets are served outside
112
185
  // Vite's module pipeline; the deck itself loads in the iframe via
113
186
  // `/index.html`, which Vite still serves normally.
114
187
  if (req.url) {
115
- const reqPath = req.url.split('?')[0];
116
188
  if (ideServer.handleHttpRequest(req, res, reqPath))
117
189
  return;
118
190
  if (agentServer.handleHttpRequest(req, res, reqPath))
119
191
  return;
120
192
  }
121
- next();
193
+ // The authenticated origin is shell-only. Never let it fall through to Vite's
194
+ // deck HTML/modules, which would put untrusted code beside the serve token.
195
+ res.writeHead(404).end();
122
196
  });
123
197
  },
124
198
  };
@@ -188,7 +262,12 @@ function readServeJson(projectDir) {
188
262
  typeof info.wsPort !== 'number' ||
189
263
  typeof info.pid !== 'number')
190
264
  return null;
191
- return { port: info.port, wsPort: info.wsPort, pid: info.pid };
265
+ return {
266
+ port: info.port,
267
+ wsPort: info.wsPort,
268
+ pid: info.pid,
269
+ contentPlayUrl: typeof info.contentPlayUrl === 'string' ? info.contentPlayUrl : undefined,
270
+ };
192
271
  }
193
272
  catch {
194
273
  return null;
@@ -313,6 +392,7 @@ export async function serve(dir, options = {}) {
313
392
  const { port, wsPort } = options.port
314
393
  ? { port: startPort, wsPort: startPort + 1 }
315
394
  : await findFreePorts(startPort);
395
+ const security = new ServeSecurity(port);
316
396
  // Local WebSocket server for SDK communication
317
397
  const castleDir = path.join(projectDir, '.castle');
318
398
  if (!fs.existsSync(castleDir))
@@ -320,7 +400,12 @@ export async function serve(dir, options = {}) {
320
400
  const logFile = path.join(castleDir, 'logs.txt');
321
401
  const screenshotsDir = path.join(castleDir, 'screenshots');
322
402
  const serveJsonPath = path.join(castleDir, 'serve.json');
323
- fs.writeFileSync(serveJsonPath, JSON.stringify({ port, wsPort, pid: process.pid }) + '\n');
403
+ fs.writeFileSync(serveJsonPath, JSON.stringify({
404
+ port,
405
+ wsPort,
406
+ pid: process.pid,
407
+ contentPlayUrl: security.localContentOrigin('play'),
408
+ }) + '\n');
324
409
  process.on('exit', () => {
325
410
  try {
326
411
  fs.unlinkSync(serveJsonPath);
@@ -337,7 +422,7 @@ export async function serve(dir, options = {}) {
337
422
  // The WS server forwards `restart` to the browser, but it also needs the
338
423
  // Vite instance so it can drop transform caches first (see invalidateModuleCaches).
339
424
  const viteHolder = { vite: null };
340
- const { broadcast } = startWSServer(wsPort, projectDir, logFile, screenshotsDir, viteHolder);
425
+ const { broadcast } = startWSServer(wsPort, projectDir, logFile, screenshotsDir, viteHolder, security);
341
426
  // The deck root `/` serves a split-view shell: the deck in an iframe plus a
342
427
  // toggle button for an xterm.js terminal. The terminal's PTY is lazy -- it
343
428
  // spawns only when a browser first opens the PTY WebSocket.
@@ -355,6 +440,8 @@ export async function serve(dir, options = {}) {
355
440
  // the watcher's files_changed already tells the shell, and the panels decide
356
441
  // for themselves what to do with it.
357
442
  invalidate: (paths) => invalidateModuleCaches(viteHolder.vite, paths),
443
+ shellBootstrap: (req) => security.shellBootstrap(req),
444
+ authorizeUpgrade: (req) => security.consumeTicket(req, 'pty'),
358
445
  });
359
446
  process.on('exit', () => ideServer.shutdown());
360
447
  // The agent panel backend: router conversation + background task agents,
@@ -363,6 +450,7 @@ export async function serve(dir, options = {}) {
363
450
  deckDir: projectDir,
364
451
  deckLabel: path.basename(projectDir),
365
452
  port,
453
+ playtestServeUrl: security.localContentOrigin('play'),
366
454
  // Same effect as the WS server's own 'restart' branch below (invalidate
367
455
  // then tell every connected tab to reload), called directly in-process
368
456
  // instead of round-tripping through a WebSocket message -- this is what
@@ -374,12 +462,13 @@ export async function serve(dir, options = {}) {
374
462
  invalidateModuleCaches(viteHolder.vite);
375
463
  broadcast({ type: 'restart' });
376
464
  },
465
+ authorizeUpgrade: (req) => security.consumeTicket(req, 'agent'),
377
466
  });
378
467
  process.on('exit', () => agentServer.shutdown());
379
468
  const vite = await createServer({
380
469
  root: projectDir,
381
470
  plugins: [
382
- castlePlugin(wsPort, ideServer, agentServer),
471
+ castlePlugin(security, ideServer, agentServer, options.host),
383
472
  forksOverlayPlugin(),
384
473
  importsAliasPlugin(),
385
474
  sceneFilesPlugin(),
@@ -399,7 +488,11 @@ export async function serve(dir, options = {}) {
399
488
  ws: true,
400
489
  },
401
490
  },
402
- fs: { strict: false },
491
+ fs: {
492
+ strict: true,
493
+ allow: [projectDir],
494
+ deny: ['.env', '.env.*', '*.pem', '*.key', '*.crt', '.castle', '.castle/**', '.git', '.git/**'],
495
+ },
403
496
  },
404
497
  logLevel: 'info',
405
498
  });
@@ -550,12 +643,25 @@ async function serveDetached(projectDir, options) {
550
643
  }
551
644
  throw new Error(`Detached serve did not write ${serveJsonPath} within 15s; check ${logPath} for startup errors.`);
552
645
  }
553
- function startWSServer(port, projectDir, logFile, screenshotsDir, viteHolder) {
646
+ function startWSServer(port, projectDir, logFile, screenshotsDir, viteHolder, security) {
554
647
  // Bind to loopback: the only reachers are same-container callers — the Vite proxy
555
648
  // (`/__castle/ws` -> `ws://localhost:${port}`) and node-side CLI clients that dial
556
649
  // `ws://localhost:${port}`. Binding 0.0.0.0 also exposed this control channel to
557
650
  // co-tenant containers across the shared Docker bridge.
558
- const wss = new WebSocketServer({ port, host: '127.0.0.1' });
651
+ const wss = new WebSocketServer({
652
+ port,
653
+ host: '127.0.0.1',
654
+ maxPayload: 12 * 1024 * 1024,
655
+ verifyClient: ({ req }, done) => {
656
+ // Node-side CLI clients are loopback and carry no browser Origin. Browser clients
657
+ // arrive through Vite's loopback proxy but must prove both origin and a one-use ticket.
658
+ if (!req.headers.origin) {
659
+ done(req.socket.remoteAddress === '127.0.0.1' || req.socket.remoteAddress === '::1');
660
+ return;
661
+ }
662
+ done(isSameOriginUpgrade(req) && security.consumeTicket(req, 'serve'));
663
+ },
664
+ });
559
665
  const clients = new Set();
560
666
  const broadcast = (msg) => {
561
667
  const data = JSON.stringify(msg);
@@ -584,7 +690,34 @@ function startWSServer(port, projectDir, logFile, screenshotsDir, viteHolder) {
584
690
  : Buffer.isBuffer(raw)
585
691
  ? raw.toString('utf8')
586
692
  : Buffer.from(raw).toString('utf8');
587
- const msg = JSON.parse(text);
693
+ let msg = JSON.parse(text);
694
+ let bridgeRole = null;
695
+ if (msg.type === 'deck_bridge') {
696
+ if ((msg.role !== 'edit' && msg.role !== 'play') ||
697
+ !msg.message ||
698
+ typeof msg.message !== 'object')
699
+ return;
700
+ bridgeRole = msg.role;
701
+ msg = msg.message;
702
+ const allowed = new Set([
703
+ 'log',
704
+ 'screenshot_response',
705
+ 'write_file',
706
+ 'castle_command',
707
+ ]);
708
+ if (!allowed.has(String(msg.type)))
709
+ return;
710
+ }
711
+ // Liveness. A client asks so it can tell a live connection from one that
712
+ // died without a close -- the state a sleeping laptop or a dropped
713
+ // network leaves behind, which `readyState` reports as OPEN forever.
714
+ // Answered here rather than with a protocol-level ping because the
715
+ // browser's WebSocket API never exposes those to page JS.
716
+ if (msg.type === 'ping') {
717
+ if (ws.readyState === WebSocket.OPEN)
718
+ ws.send(JSON.stringify({ type: 'pong' }));
719
+ return;
720
+ }
588
721
  if (msg.type === 'restart') {
589
722
  // Fire-and-forget: reload every open tab.
590
723
  invalidateModuleCaches(viteHolder.vite);
@@ -634,7 +767,8 @@ function startWSServer(port, projectDir, logFile, screenshotsDir, viteHolder) {
634
767
  }
635
768
  }
636
769
  if (msg.type === 'log') {
637
- const line = `[${msg.level}] ${msg.msg}\n`;
770
+ const body = typeof msg.msg === 'string' ? msg.msg.slice(0, 64 * 1024) : '';
771
+ const line = `[${msg.level}] ${body}\n`;
638
772
  appendCapped(logFile, line);
639
773
  if (msg.level === 'error')
640
774
  process.stderr.write(line);
@@ -677,6 +811,15 @@ function startWSServer(port, projectDir, logFile, screenshotsDir, viteHolder) {
677
811
  }
678
812
  }
679
813
  if (msg.type === 'write_file') {
814
+ if (bridgeRole === 'play') {
815
+ ws.send(JSON.stringify({
816
+ type: 'write_file_response',
817
+ requestId: msg.requestId,
818
+ ok: false,
819
+ error: 'Play frames cannot write deck files.',
820
+ }));
821
+ return;
822
+ }
680
823
  const response = writeProjectFile(projectDir, msg.path, msg.contents);
681
824
  ws.send(JSON.stringify({
682
825
  type: 'write_file_response',
@@ -0,0 +1,32 @@
1
+ import type * as http from 'http';
2
+ export type ContentRole = 'edit' | 'play';
3
+ export type SocketEndpoint = 'serve' | 'pty' | 'agent';
4
+ export declare function mintContentGrantLabel(grant: {
5
+ role: ContentRole;
6
+ publicPort: number;
7
+ sandboxId: string;
8
+ expiresAtSeconds: number;
9
+ serveNonce: string;
10
+ }, signingKey: string): string;
11
+ export declare class ServeSecurity {
12
+ private readonly publicPort;
13
+ readonly serveToken: string;
14
+ private readonly signingKey;
15
+ private readonly serveNonce;
16
+ private readonly tickets;
17
+ constructor(publicPort: number);
18
+ authorizeHttp(req: http.IncomingMessage): boolean;
19
+ issueTicket(endpoint: SocketEndpoint): string;
20
+ consumeTicket(req: http.IncomingMessage, endpoint: SocketEndpoint): boolean;
21
+ private pruneTickets;
22
+ shellBootstrap(req: http.IncomingMessage): string;
23
+ contentOrigins(req: http.IncomingMessage): {
24
+ editOrigin: string;
25
+ playOrigin: string;
26
+ };
27
+ localContentOrigin(role: ContentRole): string;
28
+ verifyContentRequest(req: http.IncomingMessage): ContentRole | null;
29
+ shellOrigin(req: http.IncomingMessage): string;
30
+ private mintContentLabel;
31
+ private contentMac;
32
+ }