castle-web-cli 0.4.139 → 0.4.141

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.js CHANGED
@@ -16,6 +16,7 @@
16
16
  // --force. Claude support can slot in later behind runAgentCli.
17
17
  import { execFileSync, spawn } from 'child_process';
18
18
  import { IMPORTS_DIR } from './imports.js';
19
+ import { isSameOriginUpgrade } from './wsOrigin.js';
19
20
  import * as fs from 'fs';
20
21
  import * as os from 'os';
21
22
  import * as path from 'path';
@@ -3852,14 +3853,26 @@ function foldRouterQueueTurn(ctx) {
3852
3853
  state.autoFoldUsed = true;
3853
3854
  broadcastQueueState(ctx);
3854
3855
  }
3855
- 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) {
3856
3865
  const { state } = ctx;
3857
3866
  // Mid-run: queue (don't interrupt). It shows as a queued row in the
3858
3867
  // composer and flushes when the current turn settles. Idle: start now.
3859
3868
  // Persist at enqueue (assign the final message id, save attachments to
3860
3869
  // disk, mirror the queue to pending-sends.json) so a restart before the
3861
3870
  // queue drains can recover the send instead of silently dropping it.
3862
- 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);
3863
3876
  const attachments = saveAttachments(ctx.attachmentsDir, id, images);
3864
3877
  state.pendingSends.push({ id, text, attachments });
3865
3878
  persistPendingSends(ctx);
@@ -3946,7 +3959,7 @@ function createRouterQueue(deps) {
3946
3959
  persistPendingSends(ctx);
3947
3960
  maybeStartRouterQueueTurn(ctx);
3948
3961
  return {
3949
- handleUserMessage: (text, images) => handleQueueUserMessage(ctx, text, images),
3962
+ handleUserMessage: (text, images, clientId) => handleQueueUserMessage(ctx, text, images, clientId),
3950
3963
  interruptRouter: () => interruptRouterQueue(ctx),
3951
3964
  cancelQueued: (index) => cancelQueuedSend(ctx, index),
3952
3965
  isRunning: () => ctx.state.routerRunning,
@@ -4086,6 +4099,21 @@ export function createAgentServer(opts) {
4086
4099
  taskStore.acknowledge(id, rejected);
4087
4100
  }
4088
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
+ }
4089
4117
  function attachClient(socket) {
4090
4118
  clients.add(socket);
4091
4119
  const hello = {
@@ -4122,7 +4150,21 @@ export function createAgentServer(opts) {
4122
4150
  const hasText = typeof msg.text === 'string' && msg.text.trim() !== '';
4123
4151
  const hasImages = Array.isArray(msg.images) && msg.images.length > 0;
4124
4152
  if (msg.type === 'user-message' && (hasText || hasImages)) {
4125
- 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
+ }
4126
4168
  }
4127
4169
  else if (msg.type === 'interrupt') {
4128
4170
  routerQueue.interruptRouter();
@@ -4170,6 +4212,14 @@ export function createAgentServer(opts) {
4170
4212
  const url = new URL(req.url ?? '/', 'http://localhost');
4171
4213
  if (url.pathname !== AGENT_WS_PATH)
4172
4214
  return false;
4215
+ // The agent socket drives the coding agent (exec, file writes) — reject any upgrade
4216
+ // that isn't same-origin (a co-tenant reaching this port directly sends no browser
4217
+ // Origin). Consumed either way so a rejected upgrade never falls through.
4218
+ if (!isSameOriginUpgrade(req)) {
4219
+ socket.write('HTTP/1.1 403 Forbidden\r\n\r\n');
4220
+ socket.destroy();
4221
+ return true;
4222
+ }
4173
4223
  wss.handleUpgrade(req, socket, head, (ws) => attachClient(ws));
4174
4224
  return true;
4175
4225
  }
package/dist/ide.js CHANGED
@@ -12,6 +12,7 @@ import picomatch from 'picomatch';
12
12
  import { fileURLToPath } from 'url';
13
13
  import { createRequire } from 'module';
14
14
  import { spawn as spawnPty } from '@lydell/node-pty';
15
+ import { isSameOriginUpgrade } from './wsOrigin.js';
15
16
  import headlessPkg from '@xterm/headless';
16
17
  import { SerializeAddon } from '@xterm/addon-serialize';
17
18
  import { WebSocketServer } from 'ws';
@@ -1107,6 +1108,14 @@ export function createIdeServer(opts) {
1107
1108
  const url = new URL(req.url ?? '/', 'http://localhost');
1108
1109
  if (url.pathname !== PTY_WS_PATH)
1109
1110
  return false;
1111
+ // The PTY is a root login shell — reject any upgrade that isn't same-origin (a
1112
+ // co-tenant reaching this port directly sends no browser Origin). Consumed either
1113
+ // way so a rejected upgrade never falls through to another handler.
1114
+ if (!isSameOriginUpgrade(req)) {
1115
+ socket.write('HTTP/1.1 403 Forbidden\r\n\r\n');
1116
+ socket.destroy();
1117
+ return true;
1118
+ }
1110
1119
  wss.handleUpgrade(req, socket, head, (ws) => attachClient(ws));
1111
1120
  return true;
1112
1121
  }
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.16';
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/serve.js CHANGED
@@ -551,7 +551,11 @@ async function serveDetached(projectDir, options) {
551
551
  throw new Error(`Detached serve did not write ${serveJsonPath} within 15s; check ${logPath} for startup errors.`);
552
552
  }
553
553
  function startWSServer(port, projectDir, logFile, screenshotsDir, viteHolder) {
554
- const wss = new WebSocketServer({ port });
554
+ // Bind to loopback: the only reachers are same-container callers — the Vite proxy
555
+ // (`/__castle/ws` -> `ws://localhost:${port}`) and node-side CLI clients that dial
556
+ // `ws://localhost:${port}`. Binding 0.0.0.0 also exposed this control channel to
557
+ // co-tenant containers across the shared Docker bridge.
558
+ const wss = new WebSocketServer({ port, host: '127.0.0.1' });
555
559
  const clients = new Set();
556
560
  const broadcast = (msg) => {
557
561
  const data = JSON.stringify(msg);
@@ -581,6 +585,16 @@ function startWSServer(port, projectDir, logFile, screenshotsDir, viteHolder) {
581
585
  ? raw.toString('utf8')
582
586
  : Buffer.from(raw).toString('utf8');
583
587
  const msg = JSON.parse(text);
588
+ // Liveness. A client asks so it can tell a live connection from one that
589
+ // died without a close -- the state a sleeping laptop or a dropped
590
+ // network leaves behind, which `readyState` reports as OPEN forever.
591
+ // Answered here rather than with a protocol-level ping because the
592
+ // browser's WebSocket API never exposes those to page JS.
593
+ if (msg.type === 'ping') {
594
+ if (ws.readyState === WebSocket.OPEN)
595
+ ws.send(JSON.stringify({ type: 'pong' }));
596
+ return;
597
+ }
584
598
  if (msg.type === 'restart') {
585
599
  // Fire-and-forget: reload every open tab.
586
600
  invalidateModuleCaches(viteHolder.vite);