castle-web-cli 0.4.141 → 0.4.144

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.
@@ -0,0 +1,236 @@
1
+ import * as crypto from 'crypto';
2
+ import * as fs from 'fs';
3
+ import * as path from 'path';
4
+ import { NO_DECK_DOCS } from './agent-prompts.js';
5
+ import { resolveFileTypes } from './editorConfig.js';
6
+ // The platform's own guidance to agents -- the rules identical in a bare deck
7
+ // and a kit deck: the card, touch, assets and formats, imports, reloading,
8
+ // editors. Its one home is here. The serve writes it under the deck's .castle/
9
+ // at every start (runtime state: not saved, not versioned, never edited), the
10
+ // deck's root CLAUDE.md `@`-imports the compact copy so any agent that
11
+ // auto-loads CLAUDE.md gets it for free, and backends that read no CLAUDE.md
12
+ // (cursor-agent, smith) get the same bullets in their composed prompt. Kits
13
+ // state only what is theirs; nothing below is restated in a kit's guide.
14
+ //
15
+ // The text is what was always in context before it had one home: the four
16
+ // sections `init` used to append to every CLAUDE.md, verbatim, plus the rules
17
+ // the kits' quick references used to restate (formats, install, reloading,
18
+ // editors) in their original wording. Nothing that was inlined became
19
+ // tool-call-only in the move, and nothing tool-call-only became inlined --
20
+ // that split is deliberate (memo 26-08-24-17-54) and the eval legs measured
21
+ // the vehicle, not a rewrite.
22
+ export const PLATFORM_DOCS_DIR = path.join('.castle', 'docs');
23
+ export const PLATFORM_DOC_REL = path.join(PLATFORM_DOCS_DIR, 'platform.md');
24
+ const MEDIA = {
25
+ images: ['.png', '.jpg', '.jpeg', '.gif', '.webp', '.svg'],
26
+ audio: ['.mp3', '.wav', '.m4a'],
27
+ video: ['.mp4'],
28
+ };
29
+ const code = (exts) => exts.map((e) => `\`${e}\``).join(' ');
30
+ // What this deck can hold: the formats that survive publishing, plus whatever
31
+ // the deck or its imports declared as a file type (a declaration is the deck
32
+ // saying it handles that format -- see editorConfig.ts). Computed per deck so
33
+ // no kit has to restate the list and no list goes stale on a deck that adds a
34
+ // type.
35
+ function mediaList(deckDir) {
36
+ const defaults = new Set([...MEDIA.images, ...MEDIA.audio, ...MEDIA.video]);
37
+ const own = (resolveFileTypes(deckDir) ?? [])
38
+ .filter((t) => !t.unsupported && !defaults.has(t.ext))
39
+ .map((t) => t.ext);
40
+ const base = `images ${code(MEDIA.images)}, audio ${code(MEDIA.audio)}, video \`.mp4\` (H.264)`;
41
+ return own.length ? `${base}, plus its own declared types ${code(own)}` : base;
42
+ }
43
+ // The ratified mode bullet (prompt-evals deliverable 4: the 169-byte line that
44
+ // is the whole difference between offering and building unasked). Verbatim.
45
+ const MODE_BULLET = "- Unprompted, an editor is an offer, never a build: when the same data keeps getting edited by hand, propose one and build on the user's yes. Never during a first build.";
46
+ // The rules that reached agents through a kit's quick reference before the
47
+ // kits stopped restating them: the physics-2d / blank wording, with the media
48
+ // list computed per deck.
49
+ export function everyDeckBullets(deckDir) {
50
+ return [
51
+ `- **Supported media formats are exactly**: ${mediaList(deckDir)}. Nothing else — a published deck inlines every asset as a \`data:\` URI, where the browser trusts the declared type instead of sniffing the bytes, so a format that merely works while serving (\`.mov\` is the classic case) can be dead once published. Convert, don't improvise.`,
52
+ "- To add an npm package, put it in `package.json` `dependencies` and run `castle-web install .` (the install `init` ran; it uses whichever package manager made the lockfile).",
53
+ "- Do not reload the deck after an edit. Nothing auto-reloads: the person applies your changes when they are ready, from the Play panel's restart button or a panel's own reload control. `npm run restart` reloads every open panel at once and breaks their flow — only when asked.",
54
+ "- The deck can define its own editors: declare a file type in `castle.json` (`editor.fileTypes`: ext, label, icon, and an `editors/` module) and the Files panel opens that type in it — whole recipe under `## Editors` in the deck's guide (its kit's `CLAUDE.md` under `imports/`). Editors under `imports/` are read-only; add or fork, don't edit.",
55
+ '- An editor is for content FILES the creator keeps coming back to (catalogs, dialogue, level tables) that nothing already opens. One-off or generated data stays code.',
56
+ MODE_BULLET,
57
+ ];
58
+ }
59
+ // The guide as a section of the prompt's "how this deck works", for the
60
+ // backends that read no CLAUDE.md. Same heading shape as an import's section.
61
+ export const PLATFORM_SECTION_HEADING = '### from the Castle platform (every deck)';
62
+ export function platformSection(deckDir) {
63
+ return `${PLATFORM_SECTION_HEADING}\n\n${platformGuide(deckDir)}`;
64
+ }
65
+ // ------------------------------------------------------------------- the gate
66
+ // Whether this serve may rewrite an EXISTING deck's root CLAUDE.md onto the
67
+ // @import. That rewrite is the one irreversible thing here, so it reaches decks
68
+ // on a gate rather than all at once; off unless the serve was told otherwise.
69
+ // Everything else is unconditional -- the guide written under .castle/docs, the
70
+ // section a new deck scaffolds with, the block spawned agents get -- because
71
+ // the kits are one shared artifact and stopped restating these rules for
72
+ // everyone at once, gate or no gate. The cloud editor sets it per user from a
73
+ // feature gate; see serveOnPort in castle-www's cloudSandbox.ts.
74
+ function mayMigrateClaudeMd() {
75
+ return process.env.CASTLE_PLATFORM_DOC === 'on';
76
+ }
77
+ // The line has to stand on its own to count: this repo's CLAUDE.md names the
78
+ // path inside a sentence, and prose about the import must not read as a deck
79
+ // carrying one.
80
+ function claudeMdImportsGuide(deckDir) {
81
+ try {
82
+ return fs
83
+ .readFileSync(path.join(deckDir, 'CLAUDE.md'), 'utf8')
84
+ .split('\n')
85
+ .some((line) => line.trim() === CLAUDE_MD_IMPORT_LINE);
86
+ }
87
+ catch {
88
+ return false;
89
+ }
90
+ }
91
+ // Resolved ONCE per deck and cached, for the reason planSession is (agent.ts):
92
+ // it decides what sits in the prompt's cached prefix, and answering a
93
+ // mid-session edit would split that cache. The serve migrates before it builds
94
+ // any prompt, so the first answer here is the post-migration one.
95
+ const guideLoaders = new Map();
96
+ function deckLoadsGuide(deckDir) {
97
+ const cached = guideLoaders.get(deckDir);
98
+ if (cached !== undefined)
99
+ return cached;
100
+ const loads = claudeMdImportsGuide(deckDir);
101
+ guideLoaders.set(deckDir, loads);
102
+ return loads;
103
+ }
104
+ // A sentence from the bullets the kits used to restate, distinctive enough to
105
+ // tell a kit guide that still carries them from one that stopped.
106
+ const RESTATEMENT_MARKER = '**Supported media formats are exactly**';
107
+ // The every-deck bullets after a quick reference that lacks them. Skipped when
108
+ // the deck's kit is pinned to a version that still restates them, which would
109
+ // otherwise say all of it twice.
110
+ function withEveryDeckBullets(deckDir, quickReference) {
111
+ const own = quickReference.trim();
112
+ if (own.includes(RESTATEMENT_MARKER))
113
+ return quickReference;
114
+ const bullets = everyDeckBullets(deckDir).join('\n');
115
+ return own ? `${own}\n\n${bullets}` : bullets;
116
+ }
117
+ // A deck's quick reference as one backend sees it. cursor-agent and smith read
118
+ // no CLAUDE.md, so the whole block goes in their prompt. claude auto-loads the
119
+ // root CLAUDE.md -- but only a deck whose file carries the @import line has the
120
+ // guide that way. A deck the migration has not reached (gated off) or refused
121
+ // ('kept' -- someone edited its sections) still has the four legacy sections
122
+ // inline and is missing just the every-deck bullets, which left the kits'
123
+ // quick reference in the same change that added the guide.
124
+ export function quickReferenceFor(deckDir, quickReference, backend) {
125
+ if (backend === 'claude') {
126
+ return deckLoadsGuide(deckDir) ? quickReference : withEveryDeckBullets(deckDir, quickReference);
127
+ }
128
+ const own = quickReference.trim();
129
+ return `${platformSection(deckDir)}\n\n${own || NO_DECK_DOCS}`;
130
+ }
131
+ // The four sections `init` appended to every deck's CLAUDE.md until 2026-08-25
132
+ // (COMMON_INSTRUCTIONS), verbatim; only the "(every deck)" heading suffix is
133
+ // gone, since the whole file is that now.
134
+ const COMMON_SECTIONS = `## Imports are read-only
135
+
136
+ - **\`imports/\` holds other decks' files and is locked read-only on disk.** Files are mode 0444 and directories 0555, so any shell command that writes, moves, or deletes inside \`imports/\` fails with \`EACCES\` / "Permission denied" — that is the lock working, not a broken checkout. Do not \`chmod\` around it, do not \`sudo\`, and do not retry the command a different way.
137
+ - **Change an import through the CLI, never the filesystem.** \`castle-web add-import <deckIdOrUrl>\` adds one and \`castle-web update-import [alias]\` re-fetches it (\`--check\` to see if it is outdated, \`--revert\` to undo). These handle the unlock/relock themselves.
138
+ - **\`castle-web list-decks [--kind mine|saved|kits]\` is how you find out WHAT can be imported** — one deck per line, starting with the id \`add-import\` takes, and marked when this deck already has it. \`imports/\` only shows what is here already; it is not a catalogue.
139
+ - **To change one file of an import, FORK it**: \`castle-web fork-import-file <path>\` takes this deck's own version of that file, and every reference to the imported path uses your version from then on (\`castle-web revert-import-file <path>\` drops it and goes back to the import's). Fork only what you actually need to change, and as few files as you can -- a forked file stops taking the import's updates, so the more you fork the less an \`update-import\` can give you. To build something of your own rather than change theirs, write an ordinary file in this deck instead -- and check first whether the kit already lets a deck file register what you want (its CLAUDE.md names those seams), since that path keeps taking updates and a fork does not. When you do fork, it is often worth forking only to add a hook or registration point and keeping the logic itself in a deck file, so later changes need no further forks; for a quick one-off tweak a plain direct fork is fine.
140
+ - **Deleting the deck directory itself needs the lock released first** (\`chmod -R u+w\` on the deck dir) — that is the one legitimate reason to touch the modes, and only for a directory being thrown away.
141
+
142
+ ## Assets
143
+
144
+ - **Load static assets (drawings, audio, etc.) through the bundler — never runtime-\`fetch\` a loose file path.** Use a static \`import\`, \`import.meta.glob('./drawings/*.svg', { eager: true, import: 'default' })\`, or inline the asset directly. The dev serve happens to serve loose files over HTTP, so \`fetch('drawings/qb.svg')\` looks like it works locally — but \`save-deck\` bundles the whole deck into a single file, loose files are no longer served, and the fetch silently fails on every platform. Kit decks: use the kit's own drawing/asset-loading APIs instead of a raw \`fetch\`.
145
+
146
+ ## Touch controls
147
+
148
+ - **Playable on a touchscreen, with only the controls the game actually needs.** Castle decks are played on phones, so whatever input a game does use must work by touch — direct tap/drag on the game itself wherever possible, and on-screen buttons only where the mechanics genuinely call for them. Do NOT add controls a game doesn't need: never drop in a generic d-pad or movement overlay by default. Prefer touching the game directly over an overlay that just mirrors keyboard keys. Keyboard input is fine to support on top for desktop play. Match the controls to the actual mechanics — a game with no directional movement should have no movement controls at all.
149
+
150
+ ## Fit the card
151
+
152
+ - **The deck plays inside a fixed 5:7 portrait card, not the full window.** The card is sized to fit the screen (at most about 450x630px), clips overflow, and does not scroll. Design the whole layout to fit inside that portrait box: size UI relative to the card with percentages, flex/grid, \`min()\`, \`clamp()\`, or viewport-relative units instead of fixed tall panels. Let playfields scale down on smaller cards rather than overflowing; anything outside the card edges is cut off. The SDK exports \`CARD_RATIO\` (= 5 / 7) if you need the exact ratio.
153
+ - **Hand-rolled \`<canvas>\` elements must account for devicePixelRatio, or the game looks blurry on phones.** Size the backing store to the CSS layout size times \`devicePixelRatio\` (e.g. \`canvas.width = rect.width * dpr\`), keep the CSS width/height as the layout size, and scale the 2D context (\`ctx.scale(dpr, dpr)\`) so drawing code stays in CSS units — re-apply on resize. Kit decks don't need to do this by hand; the kit's engine already configures its canvas for DPR.
154
+ - Exception: deliberate pixel art wants a fixed low-resolution backing store with \`image-rendering: pixelated\` CSS instead — don't DPR-scale that; the crisp chunky look is the point.
155
+ `;
156
+ export function platformGuide(deckDir) {
157
+ return `${COMMON_SECTIONS.trimEnd()}
158
+
159
+ ## Formats, reloading, editors
160
+
161
+ ${everyDeckBullets(deckDir).join('\n')}
162
+ `;
163
+ }
164
+ function platformDoc(deckDir) {
165
+ return `# Castle platform
166
+
167
+ How every Castle deck works, from the Castle CLI. Written fresh at every serve
168
+ start; the deck's own guide (its kit's CLAUDE.md under imports/) adds what its
169
+ kit provides on top of this.
170
+
171
+ ${platformGuide(deckDir)}`;
172
+ }
173
+ // Written by the serve at every start, so the copy in a deck is exactly as
174
+ // fresh as the CLI serving it.
175
+ export function writePlatformDocs(deckDir) {
176
+ fs.mkdirSync(path.join(deckDir, PLATFORM_DOCS_DIR), { recursive: true });
177
+ fs.writeFileSync(path.join(deckDir, PLATFORM_DOC_REL), platformDoc(deckDir));
178
+ }
179
+ // What the deck's root CLAUDE.md carries for the platform: one @import line
180
+ // (which claude auto-loads) inside a short section that says what it is, for
181
+ // the agents that read the file as plain text.
182
+ export const CLAUDE_MD_IMPORT_LINE = `@${PLATFORM_DOC_REL}`;
183
+ export const CLAUDE_MD_PLATFORM_SECTION = `## Platform
184
+
185
+ The rules every Castle deck plays by -- the card and touch, assets and
186
+ formats, imports, reloading, editors -- are the Castle CLI's, not this deck's.
187
+ The serve writes them fresh at every start to \`${PLATFORM_DOC_REL}\`, loaded here:
188
+
189
+ ${CLAUDE_MD_IMPORT_LINE}
190
+ `;
191
+ // ---------------------------------------------------------------- migration
192
+ // Every version of the "(every deck)" sections that `init` ever appended to a
193
+ // deck's CLAUDE.md (COMMON_INSTRUCTIONS, 2026-07 to 2026-08), as sha256 of the
194
+ // trimmed section. A deck whose sections all match one of these carried the
195
+ // platform text untouched, and the serve may replace them with the @import;
196
+ // any other section body is the deck's own and is left exactly as it is.
197
+ const LEGACY_SECTION_HASHES = new Set([
198
+ '0b7db63866c07f8346201493c45fab2ca3419f1502456dffd00a833024bc3d47', // ## Assets (every deck) @ e11bd8c
199
+ '6500b701989fb6b4dd0c2b09c7b3d38f189480c5fa7148563af894098609d5cb', // ## Castle rules (every deck) @ 289055f
200
+ '44ec1f1565f6be49f914bb7513bab37acc18ddfcb24c4d91f447a7b157d6d477', // ## Fit the card (every deck) @ 8552d0e
201
+ '97913fb5e98d7707a78db22927e8fc4a06cae8393cfdd6c61880aa100498356b', // ## Fit the card (every deck) @ 31e6897
202
+ '8a03a1826d10ba2e37ac3fc2aadc3a478051b125abf98f33073e2314e32eeae1', // ## Imports are read-only (every deck) @ 1b94488
203
+ 'daf5c57e0b14bde423efaa5c30f6f4531743be13293639b9085c14e4da0689f3', // ## Imports are read-only (every deck) @ f2d8a41
204
+ '78f0dc79715876bfb4b3b9f5f0a5469ecf8b424d995680ef28a8454293a2ff84', // ## Imports are read-only (every deck) @ 7e4a9f9
205
+ '0ae557e6602d9a03c71f45ed7516bc4808c8d166c5023512c0e6d68254704f85', // ## Touch controls (every deck) @ c9c749f
206
+ '132f2c4c13685d17cb45d775c2cce55dfbc54c79d8f9821eaea8e147567592b9', // ## Touch controls (every deck) @ bc5fbe0
207
+ ]);
208
+ const LEGACY_HEADING = /^## .*\(every deck\)\s*$/m;
209
+ const hash = (s) => crypto.createHash('sha256').update(s.trim()).digest('hex');
210
+ // Move an existing deck's root CLAUDE.md onto the @import: remove the legacy
211
+ // sections when every one of them is byte-for-byte a version this CLI shipped,
212
+ // then append the platform section. Text outside those sections is never
213
+ // touched, and a section anyone edited keeps the whole file as it is ('kept'
214
+ // -- the deck chose its text; the prompt-side block still reaches spawned
215
+ // agents). A file with no legacy sections at all just gains the section.
216
+ export function migrateClaudeMd(deckDir) {
217
+ if (!mayMigrateClaudeMd())
218
+ return 'gated';
219
+ const claudePath = path.join(deckDir, 'CLAUDE.md');
220
+ let md;
221
+ try {
222
+ md = fs.readFileSync(claudePath, 'utf8');
223
+ }
224
+ catch {
225
+ return 'absent';
226
+ }
227
+ if (md.includes(CLAUDE_MD_IMPORT_LINE))
228
+ return 'current';
229
+ const parts = md.split(/(?=^## )/m);
230
+ const legacy = parts.filter((p) => LEGACY_HEADING.test(p.split('\n')[0]));
231
+ if (legacy.some((p) => !LEGACY_SECTION_HASHES.has(hash(p))))
232
+ return 'kept';
233
+ const rest = parts.filter((p) => !legacy.includes(p)).join('').trimEnd();
234
+ fs.writeFileSync(claudePath, `${rest}\n\n${CLAUDE_MD_PLATFORM_SECTION}`);
235
+ return legacy.length ? 'migrated' : 'added';
236
+ }
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,6 @@
1
1
  export declare function appendCapped(file: string, line: string): void;
2
+ export declare function isAllowedShellHost(hostHeader: string | undefined, configuredHost?: string): boolean;
3
+ export declare function isAllowedContentFilesRequest(role: 'edit' | 'play' | null, method: string | undefined, reqPath: string): boolean;
2
4
  export declare function serve(dir: string, options?: {
3
5
  port?: string;
4
6
  host?: string;
package/dist/serve.js CHANGED
@@ -4,15 +4,20 @@ 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';
11
12
  import { autoUpdateImports, IMPORTS_DIR, lockImportTree } from './imports.js';
13
+ import { ensureAgentsSymlink } from './init.js';
14
+ import { migrateClaudeMd, PLATFORM_DOC_REL, writePlatformDocs } from './platformDoc.js';
12
15
  import { FORKS_DIR, ownForkFile, splitImportRel } from './forks.js';
13
16
  import * as config from './config.js';
14
17
  import { graphql as castleGraphql } from './api.js';
15
18
  import { executeCommand } from './castle-host/host.js';
19
+ import { ServeSecurity } from './serveSecurity.js';
20
+ import { isSameOriginUpgrade } from './wsOrigin.js';
16
21
  // The log is a tail, not an archive: append, and once it passes the cap drop
17
22
  // whole lines off the front until it is back under.
18
23
  const LOG_MAX_BYTES = 2 * 1024 * 1024;
@@ -74,7 +79,40 @@ const CONSOLE_CAPTURE = `<script>(function(){
74
79
  };
75
80
  });
76
81
  })();</script>`;
77
- function castlePlugin(wsPort, ideServer, agentServer) {
82
+ function hostnameFromHeader(value) {
83
+ if (!value)
84
+ return '';
85
+ if (value.startsWith('[')) {
86
+ const end = value.indexOf(']');
87
+ return end > 0 ? value.slice(1, end).toLowerCase() : '';
88
+ }
89
+ return value.split(':')[0].toLowerCase();
90
+ }
91
+ export function isAllowedShellHost(hostHeader, configuredHost) {
92
+ const host = hostnameFromHeader(hostHeader);
93
+ if (!host)
94
+ return false;
95
+ if (host === 'localhost' || isIP(host) !== 0)
96
+ return true;
97
+ if (/^\d+-[a-z0-9]{14}\.sandboxes(?:-staging)?\.castle\.xyz$/.test(host))
98
+ return true;
99
+ // Preserve explicit LAN/tailnet development without accepting arbitrary DNS-rebinding hosts.
100
+ if (host.endsWith('.local') || host.endsWith('.ts.net'))
101
+ return true;
102
+ const configured = configuredHost ? hostnameFromHeader(configuredHost) : '';
103
+ return configured !== '' && configured !== '0.0.0.0' && configured !== '::' && host === configured;
104
+ }
105
+ const EDIT_CONTENT_READ_ENDPOINTS = new Set([
106
+ '/__castle/files/raw',
107
+ '/__castle/files/read',
108
+ '/__castle/files/info',
109
+ '/__castle/files/list',
110
+ '/__castle/files/forks',
111
+ ]);
112
+ export function isAllowedContentFilesRequest(role, method, reqPath) {
113
+ return role === 'edit' && method === 'GET' && EDIT_CONTENT_READ_ENDPOINTS.has(reqPath);
114
+ }
115
+ function castlePlugin(security, ideServer, agentServer, configuredHost) {
78
116
  return {
79
117
  name: 'castle-dev',
80
118
  transformIndexHtml: {
@@ -88,37 +126,85 @@ function castlePlugin(wsPort, ideServer, agentServer) {
88
126
  const favicon = /<link[^>]+rel=["']?[^"'>]*icon/i.test(html)
89
127
  ? ''
90
128
  : `\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}`);
129
+ return html.replace(/<head(\s[^>]*)?>/i, (match) => `${match}${favicon}\n <script>
130
+ window.CastleEmbed={edit:true,host:'dev'};
131
+ window.__castleShellOrigin=(function(){
132
+ var h=location.hostname.toLowerCase(),m=/^1[ep]([0-9a-z]{1,4})-([a-z0-9]{14})-/.exec(h);
133
+ if(!m)return null;
134
+ var p=parseInt(m[1],36),sid=m[2];
135
+ if(h.endsWith('.sandboxes-staging.castlexyz.com'))return 'https://'+p+'-'+sid+'.sandboxes-staging.castle.xyz';
136
+ if(h.endsWith('.sandboxes.castlexyz.com'))return 'https://'+p+'-'+sid+'.sandboxes.castle.xyz';
137
+ return null;
138
+ })();
139
+ </script>\n ${CONSOLE_CAPTURE}`);
92
140
  },
93
141
  },
94
142
  configureServer(server) {
95
143
  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' }));
144
+ const reqPath = (req.url || '/').split('?')[0];
145
+ const trustedSurface = req.headers['x-castle-sandbox-surface'];
146
+ const verifiedRole = security.verifyContentRequest(req);
147
+ const content = trustedSurface === 'content' || verifiedRole !== null;
148
+ if (content && !verifiedRole) {
149
+ res.writeHead(403).end('invalid content capability');
99
150
  return;
100
151
  }
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() }));
152
+ if (!content && !isAllowedShellHost(req.headers.host, configuredHost)) {
153
+ res.writeHead(403).end('untrusted host');
104
154
  return;
105
155
  }
106
- if (req.url === '/__castle/context') {
107
- res.writeHead(200, { 'Content-Type': 'application/json' });
108
- res.end(JSON.stringify(readDeckContext(server.config.root)));
156
+ if (reqPath === '/__castle/ws-ticket') {
157
+ if (content || req.method !== 'POST' || !security.authorizeHttp(req)) {
158
+ res.writeHead(403).end();
159
+ return;
160
+ }
161
+ const endpoint = new URL(req.url || '/', 'http://localhost').searchParams.get('endpoint');
162
+ if (endpoint !== 'serve' && endpoint !== 'pty' && endpoint !== 'agent') {
163
+ res.writeHead(400).end('invalid endpoint');
164
+ return;
165
+ }
166
+ res.writeHead(200, { 'content-type': 'application/json', 'cache-control': 'no-store' });
167
+ res.end(JSON.stringify({ ticket: security.issueTicket(endpoint) }));
168
+ return;
169
+ }
170
+ if (reqPath === '/__castle/auth' || reqPath === '/__castle/ws-port' || reqPath === '/__castle/context') {
171
+ res.writeHead(404).end();
172
+ return;
173
+ }
174
+ if (content) {
175
+ if (reqPath === '/')
176
+ req.url = `/index.html${req.url?.includes('?') ? req.url.slice(req.url.indexOf('?')) : ''}`;
177
+ const allowedFilesRequest = isAllowedContentFilesRequest(verifiedRole, req.method, reqPath);
178
+ const allowedVendor = reqPath.startsWith('/__castle/vendor/');
179
+ const allowedFavicon = FAVICON_FILES.some((name) => reqPath === `/${name}`);
180
+ if (reqPath.startsWith('/__castle/') && !allowedFilesRequest && !allowedVendor) {
181
+ res.writeHead(403).end('content capability does not allow this endpoint');
182
+ return;
183
+ }
184
+ if ((allowedFilesRequest || allowedVendor || allowedFavicon) && ideServer.handleHttpRequest(req, res, reqPath))
185
+ return;
186
+ next();
187
+ return;
188
+ }
189
+ const publicShellPath = reqPath === '/' ||
190
+ reqPath.startsWith('/__castle/ide/') ||
191
+ FAVICON_FILES.some((name) => reqPath === `/${name}`);
192
+ if (reqPath.startsWith('/__castle/') && !publicShellPath && !security.authorizeHttp(req)) {
193
+ res.writeHead(403).end();
109
194
  return;
110
195
  }
111
196
  // The split-view shell (`/`) + its static assets are served outside
112
197
  // Vite's module pipeline; the deck itself loads in the iframe via
113
198
  // `/index.html`, which Vite still serves normally.
114
199
  if (req.url) {
115
- const reqPath = req.url.split('?')[0];
116
200
  if (ideServer.handleHttpRequest(req, res, reqPath))
117
201
  return;
118
202
  if (agentServer.handleHttpRequest(req, res, reqPath))
119
203
  return;
120
204
  }
121
- next();
205
+ // The authenticated origin is shell-only. Never let it fall through to Vite's
206
+ // deck HTML/modules, which would put untrusted code beside the serve token.
207
+ res.writeHead(404).end();
122
208
  });
123
209
  },
124
210
  };
@@ -188,7 +274,12 @@ function readServeJson(projectDir) {
188
274
  typeof info.wsPort !== 'number' ||
189
275
  typeof info.pid !== 'number')
190
276
  return null;
191
- return { port: info.port, wsPort: info.wsPort, pid: info.pid };
277
+ return {
278
+ port: info.port,
279
+ wsPort: info.wsPort,
280
+ pid: info.pid,
281
+ contentPlayUrl: typeof info.contentPlayUrl === 'string' ? info.contentPlayUrl : undefined,
282
+ };
192
283
  }
193
284
  catch {
194
285
  return null;
@@ -313,14 +404,32 @@ export async function serve(dir, options = {}) {
313
404
  const { port, wsPort } = options.port
314
405
  ? { port: startPort, wsPort: startPort + 1 }
315
406
  : await findFreePorts(startPort);
407
+ const security = new ServeSecurity(port);
316
408
  // Local WebSocket server for SDK communication
317
409
  const castleDir = path.join(projectDir, '.castle');
318
410
  if (!fs.existsSync(castleDir))
319
411
  fs.mkdirSync(castleDir, { recursive: true });
412
+ // The platform guide, fresh from this CLI, and the root CLAUDE.md's @import
413
+ // of it (platformDoc.ts). After autoUpdateImports, so the guide's media list
414
+ // sees the imports this serve will run with.
415
+ writePlatformDocs(projectDir);
416
+ const migration = migrateClaudeMd(projectDir);
417
+ ensureAgentsSymlink(projectDir);
418
+ if (migration === 'migrated' || migration === 'added') {
419
+ console.log(`CLAUDE.md now loads the platform guide from ${PLATFORM_DOC_REL}`);
420
+ }
421
+ else if (migration === 'kept') {
422
+ console.log(`CLAUDE.md has hand-edited platform sections; left as they are (the platform guide is at ${PLATFORM_DOC_REL})`);
423
+ }
320
424
  const logFile = path.join(castleDir, 'logs.txt');
321
425
  const screenshotsDir = path.join(castleDir, 'screenshots');
322
426
  const serveJsonPath = path.join(castleDir, 'serve.json');
323
- fs.writeFileSync(serveJsonPath, JSON.stringify({ port, wsPort, pid: process.pid }) + '\n');
427
+ fs.writeFileSync(serveJsonPath, JSON.stringify({
428
+ port,
429
+ wsPort,
430
+ pid: process.pid,
431
+ contentPlayUrl: security.localContentOrigin('play'),
432
+ }) + '\n');
324
433
  process.on('exit', () => {
325
434
  try {
326
435
  fs.unlinkSync(serveJsonPath);
@@ -337,7 +446,7 @@ export async function serve(dir, options = {}) {
337
446
  // The WS server forwards `restart` to the browser, but it also needs the
338
447
  // Vite instance so it can drop transform caches first (see invalidateModuleCaches).
339
448
  const viteHolder = { vite: null };
340
- const { broadcast } = startWSServer(wsPort, projectDir, logFile, screenshotsDir, viteHolder);
449
+ const { broadcast } = startWSServer(wsPort, projectDir, logFile, screenshotsDir, viteHolder, security);
341
450
  // The deck root `/` serves a split-view shell: the deck in an iframe plus a
342
451
  // toggle button for an xterm.js terminal. The terminal's PTY is lazy -- it
343
452
  // spawns only when a browser first opens the PTY WebSocket.
@@ -355,6 +464,8 @@ export async function serve(dir, options = {}) {
355
464
  // the watcher's files_changed already tells the shell, and the panels decide
356
465
  // for themselves what to do with it.
357
466
  invalidate: (paths) => invalidateModuleCaches(viteHolder.vite, paths),
467
+ shellBootstrap: (req) => security.shellBootstrap(req),
468
+ authorizeUpgrade: (req) => security.consumeTicket(req, 'pty'),
358
469
  });
359
470
  process.on('exit', () => ideServer.shutdown());
360
471
  // The agent panel backend: router conversation + background task agents,
@@ -363,6 +474,7 @@ export async function serve(dir, options = {}) {
363
474
  deckDir: projectDir,
364
475
  deckLabel: path.basename(projectDir),
365
476
  port,
477
+ playtestServeUrl: security.localContentOrigin('play'),
366
478
  // Same effect as the WS server's own 'restart' branch below (invalidate
367
479
  // then tell every connected tab to reload), called directly in-process
368
480
  // instead of round-tripping through a WebSocket message -- this is what
@@ -374,12 +486,13 @@ export async function serve(dir, options = {}) {
374
486
  invalidateModuleCaches(viteHolder.vite);
375
487
  broadcast({ type: 'restart' });
376
488
  },
489
+ authorizeUpgrade: (req) => security.consumeTicket(req, 'agent'),
377
490
  });
378
491
  process.on('exit', () => agentServer.shutdown());
379
492
  const vite = await createServer({
380
493
  root: projectDir,
381
494
  plugins: [
382
- castlePlugin(wsPort, ideServer, agentServer),
495
+ castlePlugin(security, ideServer, agentServer, options.host),
383
496
  forksOverlayPlugin(),
384
497
  importsAliasPlugin(),
385
498
  sceneFilesPlugin(),
@@ -399,7 +512,11 @@ export async function serve(dir, options = {}) {
399
512
  ws: true,
400
513
  },
401
514
  },
402
- fs: { strict: false },
515
+ fs: {
516
+ strict: true,
517
+ allow: [projectDir],
518
+ deny: ['.env', '.env.*', '*.pem', '*.key', '*.crt', '.castle', '.castle/**', '.git', '.git/**'],
519
+ },
403
520
  },
404
521
  logLevel: 'info',
405
522
  });
@@ -550,12 +667,25 @@ async function serveDetached(projectDir, options) {
550
667
  }
551
668
  throw new Error(`Detached serve did not write ${serveJsonPath} within 15s; check ${logPath} for startup errors.`);
552
669
  }
553
- function startWSServer(port, projectDir, logFile, screenshotsDir, viteHolder) {
670
+ function startWSServer(port, projectDir, logFile, screenshotsDir, viteHolder, security) {
554
671
  // Bind to loopback: the only reachers are same-container callers — the Vite proxy
555
672
  // (`/__castle/ws` -> `ws://localhost:${port}`) and node-side CLI clients that dial
556
673
  // `ws://localhost:${port}`. Binding 0.0.0.0 also exposed this control channel to
557
674
  // co-tenant containers across the shared Docker bridge.
558
- const wss = new WebSocketServer({ port, host: '127.0.0.1' });
675
+ const wss = new WebSocketServer({
676
+ port,
677
+ host: '127.0.0.1',
678
+ maxPayload: 12 * 1024 * 1024,
679
+ verifyClient: ({ req }, done) => {
680
+ // Node-side CLI clients are loopback and carry no browser Origin. Browser clients
681
+ // arrive through Vite's loopback proxy but must prove both origin and a one-use ticket.
682
+ if (!req.headers.origin) {
683
+ done(req.socket.remoteAddress === '127.0.0.1' || req.socket.remoteAddress === '::1');
684
+ return;
685
+ }
686
+ done(isSameOriginUpgrade(req) && security.consumeTicket(req, 'serve'));
687
+ },
688
+ });
559
689
  const clients = new Set();
560
690
  const broadcast = (msg) => {
561
691
  const data = JSON.stringify(msg);
@@ -584,7 +714,24 @@ function startWSServer(port, projectDir, logFile, screenshotsDir, viteHolder) {
584
714
  : Buffer.isBuffer(raw)
585
715
  ? raw.toString('utf8')
586
716
  : Buffer.from(raw).toString('utf8');
587
- const msg = JSON.parse(text);
717
+ let msg = JSON.parse(text);
718
+ let bridgeRole = null;
719
+ if (msg.type === 'deck_bridge') {
720
+ if ((msg.role !== 'edit' && msg.role !== 'play') ||
721
+ !msg.message ||
722
+ typeof msg.message !== 'object')
723
+ return;
724
+ bridgeRole = msg.role;
725
+ msg = msg.message;
726
+ const allowed = new Set([
727
+ 'log',
728
+ 'screenshot_response',
729
+ 'write_file',
730
+ 'castle_command',
731
+ ]);
732
+ if (!allowed.has(String(msg.type)))
733
+ return;
734
+ }
588
735
  // Liveness. A client asks so it can tell a live connection from one that
589
736
  // died without a close -- the state a sleeping laptop or a dropped
590
737
  // network leaves behind, which `readyState` reports as OPEN forever.
@@ -644,7 +791,8 @@ function startWSServer(port, projectDir, logFile, screenshotsDir, viteHolder) {
644
791
  }
645
792
  }
646
793
  if (msg.type === 'log') {
647
- const line = `[${msg.level}] ${msg.msg}\n`;
794
+ const body = typeof msg.msg === 'string' ? msg.msg.slice(0, 64 * 1024) : '';
795
+ const line = `[${msg.level}] ${body}\n`;
648
796
  appendCapped(logFile, line);
649
797
  if (msg.level === 'error')
650
798
  process.stderr.write(line);
@@ -687,6 +835,15 @@ function startWSServer(port, projectDir, logFile, screenshotsDir, viteHolder) {
687
835
  }
688
836
  }
689
837
  if (msg.type === 'write_file') {
838
+ if (bridgeRole === 'play') {
839
+ ws.send(JSON.stringify({
840
+ type: 'write_file_response',
841
+ requestId: msg.requestId,
842
+ ok: false,
843
+ error: 'Play frames cannot write deck files.',
844
+ }));
845
+ return;
846
+ }
690
847
  const response = writeProjectFile(projectDir, msg.path, msg.contents);
691
848
  ws.send(JSON.stringify({
692
849
  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
+ }