castle-web-cli 0.4.141 → 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
@@ -3995,7 +3995,7 @@ export function createAgentServer(opts) {
3995
3995
  // 127.0.0.1 never answers there, and playtest would fail every call
3996
3996
  // with a navigation error. `localhost` resolves correctly under
3997
3997
  // every binding mode (default ::1, --host 0.0.0.0, explicit IPs).
3998
- serveUrl: `http://localhost:${opts.port}`,
3998
+ serveUrl: opts.playtestServeUrl ?? `http://localhost:${opts.port}`,
3999
3999
  // Kicks off the one-time Chromium download in the background at
4000
4000
  // smith-task start (see runTaskAgentIn) -- single-flight with any
4001
4001
  // real playtest call, silent on every failure path.
@@ -4215,7 +4215,7 @@ export function createAgentServer(opts) {
4215
4215
  // The agent socket drives the coding agent (exec, file writes) — reject any upgrade
4216
4216
  // that isn't same-origin (a co-tenant reaching this port directly sends no browser
4217
4217
  // Origin). Consumed either way so a rejected upgrade never falls through.
4218
- if (!isSameOriginUpgrade(req)) {
4218
+ if (!isSameOriginUpgrade(req) || (opts.authorizeUpgrade && !opts.authorizeUpgrade(req, 'agent'))) {
4219
4219
  socket.write('HTTP/1.1 403 Forbidden\r\n\r\n');
4220
4220
  socket.destroy();
4221
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.16';
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');
138
+ return;
139
+ }
140
+ if (!content && !isAllowedShellHost(req.headers.host, configuredHost)) {
141
+ res.writeHead(403).end('untrusted host');
99
142
  return;
100
143
  }
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() }));
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) }));
104
156
  return;
105
157
  }
106
- if (req.url === '/__castle/context') {
107
- res.writeHead(200, { 'Content-Type': 'application/json' });
108
- res.end(JSON.stringify(readDeckContext(server.config.root)));
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,24 @@ 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
+ }
588
711
  // Liveness. A client asks so it can tell a live connection from one that
589
712
  // died without a close -- the state a sleeping laptop or a dropped
590
713
  // network leaves behind, which `readyState` reports as OPEN forever.
@@ -644,7 +767,8 @@ function startWSServer(port, projectDir, logFile, screenshotsDir, viteHolder) {
644
767
  }
645
768
  }
646
769
  if (msg.type === 'log') {
647
- 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`;
648
772
  appendCapped(logFile, line);
649
773
  if (msg.level === 'error')
650
774
  process.stderr.write(line);
@@ -687,6 +811,15 @@ function startWSServer(port, projectDir, logFile, screenshotsDir, viteHolder) {
687
811
  }
688
812
  }
689
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
+ }
690
823
  const response = writeProjectFile(projectDir, msg.path, msg.contents);
691
824
  ws.send(JSON.stringify({
692
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
+ }
@@ -0,0 +1,193 @@
1
+ import { createHmac, randomBytes, timingSafeEqual } from 'crypto';
2
+ const CROCKFORD = '0123456789abcdefghjkmnpqrstvwxyz';
3
+ const CONTENT_LABEL_RE = /^1([ep])([0-9a-z]{1,4})-([a-z0-9]{14})-([0-9a-z]{1,8})-([0-9a-hjkmnp-tv-z]{13})-([0-9a-hjkmnp-tv-z]{20})$/;
4
+ const MAX_GRANT_SECONDS = 12 * 60 * 60;
5
+ const GRANT_CLOCK_SKEW_SECONDS = 60;
6
+ function base32Lower(bytes) {
7
+ let bits = 0;
8
+ let value = 0;
9
+ let out = '';
10
+ for (const byte of bytes) {
11
+ value = (value << 8) | byte;
12
+ bits += 8;
13
+ while (bits >= 5) {
14
+ out += CROCKFORD[(value >>> (bits - 5)) & 31];
15
+ bits -= 5;
16
+ }
17
+ }
18
+ if (bits > 0)
19
+ out += CROCKFORD[(value << (5 - bits)) & 31];
20
+ return out;
21
+ }
22
+ function safeEqual(a, b) {
23
+ const aa = Buffer.from(a);
24
+ const bb = Buffer.from(b);
25
+ return aa.length === bb.length && timingSafeEqual(aa, bb);
26
+ }
27
+ function hostWithoutPort(host) {
28
+ if (host.startsWith('['))
29
+ return host.slice(0, host.indexOf(']') + 1).toLowerCase();
30
+ return host.split(':')[0].toLowerCase();
31
+ }
32
+ function requestOrigin(req) {
33
+ const forwarded = req.headers['x-forwarded-proto'];
34
+ const protocol = typeof forwarded === 'string' ? forwarded.split(',')[0] : 'http';
35
+ return `${protocol}://${req.headers.host}`;
36
+ }
37
+ export function mintContentGrantLabel(grant, signingKey) {
38
+ const input = [
39
+ 'castle-content-v1',
40
+ grant.role,
41
+ String(grant.publicPort),
42
+ grant.sandboxId,
43
+ String(grant.expiresAtSeconds),
44
+ grant.serveNonce,
45
+ ].join('\n');
46
+ const mac = base32Lower(createHmac('sha256', signingKey).update(input).digest().subarray(0, 12));
47
+ const roleCode = grant.role === 'edit' ? 'e' : 'p';
48
+ return `1${roleCode}${grant.publicPort.toString(36)}-${grant.sandboxId}-${grant.expiresAtSeconds.toString(36)}-${grant.serveNonce}-${mac}`;
49
+ }
50
+ export class ServeSecurity {
51
+ publicPort;
52
+ serveToken = randomBytes(32).toString('base64url');
53
+ signingKey = process.env.CASTLE_AGENT_TOKEN || randomBytes(32).toString('base64url');
54
+ serveNonce = base32Lower(randomBytes(8));
55
+ tickets = new Map();
56
+ constructor(publicPort) {
57
+ this.publicPort = publicPort;
58
+ }
59
+ authorizeHttp(req) {
60
+ const value = req.headers['x-castle-serve-token'];
61
+ return typeof value === 'string' && safeEqual(value, this.serveToken);
62
+ }
63
+ issueTicket(endpoint) {
64
+ this.pruneTickets();
65
+ const ticket = randomBytes(16).toString('base64url');
66
+ this.tickets.set(ticket, { endpoint, expiresAt: Date.now() + 30_000 });
67
+ return ticket;
68
+ }
69
+ consumeTicket(req, endpoint) {
70
+ this.pruneTickets();
71
+ let ticket = '';
72
+ try {
73
+ ticket = new URL(req.url || '/', 'http://localhost').searchParams.get('ticket') || '';
74
+ }
75
+ catch {
76
+ return false;
77
+ }
78
+ const record = this.tickets.get(ticket);
79
+ if (!record)
80
+ return false;
81
+ this.tickets.delete(ticket);
82
+ return record.endpoint === endpoint && record.expiresAt > Date.now();
83
+ }
84
+ pruneTickets() {
85
+ const now = Date.now();
86
+ for (const [ticket, record] of this.tickets) {
87
+ if (record.expiresAt <= now)
88
+ this.tickets.delete(ticket);
89
+ }
90
+ }
91
+ shellBootstrap(req) {
92
+ const { editOrigin, playOrigin } = this.contentOrigins(req);
93
+ let hostOrigin = null;
94
+ try {
95
+ const referrer = typeof req.headers.referer === 'string' ? new URL(req.headers.referer) : null;
96
+ hostOrigin =
97
+ referrer &&
98
+ referrer.protocol === 'https:' &&
99
+ (referrer.hostname === 'castle.xyz' || referrer.hostname.endsWith('.castle.xyz'))
100
+ ? referrer.origin
101
+ : null;
102
+ }
103
+ catch {
104
+ /* absent or malformed referrer */
105
+ }
106
+ if (!hostOrigin &&
107
+ /\.sandboxes(?:-staging)?\.castle\.xyz(?::\d+)?$/i.test(req.headers.host || '')) {
108
+ hostOrigin = 'https://castle.xyz';
109
+ }
110
+ return `<script>(function(){
111
+ window.__CASTLE_SERVE_TOKEN__=${JSON.stringify(this.serveToken)};
112
+ window.__CASTLE_CONTENT_ORIGINS__=${JSON.stringify({ edit: editOrigin, play: playOrigin })};
113
+ window.__CASTLE_HOST_ORIGIN__=${JSON.stringify(hostOrigin)};
114
+ var nativeFetch=window.fetch.bind(window);
115
+ window.fetch=function(input,init){
116
+ try {
117
+ var u=new URL(typeof input==='string'?input:input.url,location.href);
118
+ if(u.origin===location.origin&&u.pathname.indexOf('/__castle/')===0){
119
+ init=Object.assign({},init||{});
120
+ var h=new Headers(init.headers||(typeof input!=='string'&&input.headers)||undefined);
121
+ h.set('X-Castle-Serve-Token',window.__CASTLE_SERVE_TOKEN__);
122
+ init.headers=h;
123
+ }
124
+ }catch(e){}
125
+ return nativeFetch(input,init);
126
+ };
127
+ })();</script>`;
128
+ }
129
+ contentOrigins(req) {
130
+ const host = hostWithoutPort(req.headers.host || 'localhost');
131
+ const cloud = host.match(/^\d+-([a-z0-9]{14})\.(sandboxes(?:-staging)?\.castle\.xyz)$/);
132
+ const sandboxId = cloud?.[1] || 'localdev000000';
133
+ const contentHeader = req.headers['x-castle-content-domain'];
134
+ const contentDomain = typeof contentHeader === 'string' &&
135
+ /^(?:sandboxes|sandboxes-staging)\.castlexyz\.com$/.test(contentHeader)
136
+ ? contentHeader.toLowerCase()
137
+ : cloud?.[2] === 'sandboxes-staging.castle.xyz'
138
+ ? 'sandboxes-staging.castlexyz.com'
139
+ : cloud
140
+ ? 'sandboxes.castlexyz.com'
141
+ : 'localhost';
142
+ // Leave room for small positive clock skew at the control plane. Ghost still
143
+ // enforces the hard 12-hour maximum when it resolves the capability.
144
+ const expiresAtSeconds = Math.floor(Date.now() / 1000) + MAX_GRANT_SECONDS - GRANT_CLOCK_SKEW_SECONDS;
145
+ const originFor = (role) => {
146
+ const label = this.mintContentLabel(role, sandboxId, expiresAtSeconds);
147
+ return cloud
148
+ ? `https://${label}.${contentDomain}`
149
+ : `${requestOrigin(req).split('://')[0]}://${label}.localhost:${this.publicPort}`;
150
+ };
151
+ return { editOrigin: originFor('edit'), playOrigin: originFor('play') };
152
+ }
153
+ 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}`;
157
+ }
158
+ verifyContentRequest(req) {
159
+ const host = hostWithoutPort(req.headers.host || '');
160
+ const label = host.split('.')[0];
161
+ const match = CONTENT_LABEL_RE.exec(label);
162
+ if (!match)
163
+ return null;
164
+ const publicPort = Number.parseInt(match[2], 36);
165
+ const expiresAtSeconds = Number.parseInt(match[4], 36);
166
+ const role = match[1] === 'e' ? 'edit' : 'play';
167
+ if (publicPort !== this.publicPort ||
168
+ expiresAtSeconds <= Math.floor(Date.now() / 1000) ||
169
+ expiresAtSeconds > Math.floor(Date.now() / 1000) + MAX_GRANT_SECONDS ||
170
+ match[5] !== this.serveNonce) {
171
+ return null;
172
+ }
173
+ const expected = this.contentMac(role, publicPort, match[3], expiresAtSeconds, match[5]);
174
+ return safeEqual(expected, match[6]) ? role : null;
175
+ }
176
+ shellOrigin(req) {
177
+ return requestOrigin(req);
178
+ }
179
+ mintContentLabel(role, sandboxId, expiresAtSeconds) {
180
+ return mintContentGrantLabel({
181
+ role,
182
+ publicPort: this.publicPort,
183
+ sandboxId,
184
+ expiresAtSeconds,
185
+ serveNonce: this.serveNonce,
186
+ }, this.signingKey);
187
+ }
188
+ contentMac(role, publicPort, sandboxId, expiresAtSeconds, serveNonce) {
189
+ return mintContentGrantLabel({ role, publicPort, sandboxId, expiresAtSeconds, serveNonce }, this.signingKey)
190
+ .split('-')
191
+ .at(-1);
192
+ }
193
+ }