castle-web-cli 0.4.150 → 0.4.152

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
@@ -78,6 +78,7 @@ export declare function createAgentServer(opts: {
78
78
  deckLabel: string;
79
79
  port?: number;
80
80
  playtestServeUrl?: string;
81
+ browserContentUrl?: () => string | null;
81
82
  restart?: () => void;
82
83
  authorizeUpgrade?: (req: http.IncomingMessage, endpoint: 'agent') => boolean;
83
84
  }): AgentServer;
package/dist/agent.js CHANGED
@@ -36,6 +36,7 @@ import { cancelLogin, logout, startLogin, submitLoginCode } from './byo-login.js
36
36
  import { runAgentNative } from './native/loop.js';
37
37
  import { createPlaytestBrowserManager, } from './native/playtest-browser.js';
38
38
  import { createPlaywrightPlaytestExecutor } from './native/playtest-executor.js';
39
+ import { createRemotePlaytestExecutor } from './native/playtest-remote.js';
39
40
  export const AGENT_WS_PATH = '/__castle/agent';
40
41
  export const AGENT_ATTACHMENT_PREFIX = '/__castle/agent/attachments/';
41
42
  // Playtest frame PNGs (tasks/<id>/playtest/<file>.png), served for the
@@ -3988,10 +3989,15 @@ export function createAgentServer(opts) {
3988
3989
  // playtest call (each call still gets its own fresh browser context +
3989
3990
  // page -- see playtest-executor.ts). Lazily launched on first use; never
3990
3991
  // touched at all if no task ever calls playtest.
3991
- const playtestBrowserManager = createPlaytestBrowserManager();
3992
+ const remotePlaytest = opts.browserContentUrl
3993
+ ? createRemotePlaytestExecutor(opts.browserContentUrl)
3994
+ : null;
3995
+ const playtestBrowserManager = remotePlaytest
3996
+ ? null
3997
+ : createPlaytestBrowserManager();
3992
3998
  const playtest = opts.port
3993
3999
  ? {
3994
- executor: createPlaywrightPlaytestExecutor(playtestBrowserManager),
4000
+ executor: remotePlaytest ?? createPlaywrightPlaytestExecutor(playtestBrowserManager),
3995
4001
  // `localhost`, NOT 127.0.0.1: a serve started without --host leaves
3996
4002
  // Vite on its default host, which binds ONLY [::1] on macOS --
3997
4003
  // 127.0.0.1 never answers there, and playtest would fail every call
@@ -4001,7 +4007,9 @@ export function createAgentServer(opts) {
4001
4007
  // Kicks off the one-time Chromium download in the background at
4002
4008
  // smith-task start (see runTaskAgentIn) -- single-flight with any
4003
4009
  // real playtest call, silent on every failure path.
4004
- prewarm: () => playtestBrowserManager.prewarm(),
4010
+ prewarm: playtestBrowserManager
4011
+ ? () => playtestBrowserManager.prewarm()
4012
+ : undefined,
4005
4013
  }
4006
4014
  : undefined;
4007
4015
  const taskChildren = new Set();
@@ -4246,7 +4254,7 @@ export function createAgentServer(opts) {
4246
4254
  usageFeed.stop();
4247
4255
  accountsFeed.stop();
4248
4256
  wss.close();
4249
- void playtestBrowserManager.shutdown();
4257
+ void playtestBrowserManager?.shutdown();
4250
4258
  }
4251
4259
  return { handleUpgrade, handleHttpRequest, shutdown };
4252
4260
  }
package/dist/api.d.ts CHANGED
@@ -5,7 +5,33 @@ interface GraphqlResponse {
5
5
  extensions?: Record<string, unknown>;
6
6
  }>;
7
7
  }
8
- export declare function graphql(query: string, variables?: Record<string, unknown>): Promise<GraphqlResponse>;
8
+ export declare function graphql(query: string, variables?: Record<string, unknown>, options?: {
9
+ timeoutMs?: number;
10
+ signal?: AbortSignal;
11
+ }): Promise<GraphqlResponse>;
12
+ export type BrowserOperation = {
13
+ kind: 'playtest';
14
+ durationMs: number;
15
+ actions: Array<{
16
+ t: number;
17
+ type: 'down' | 'move' | 'up' | 'tap' | 'key';
18
+ x?: number;
19
+ y?: number;
20
+ key?: string;
21
+ durationMs?: number;
22
+ }>;
23
+ screenshots: number[];
24
+ } | {
25
+ kind: 'cover';
26
+ };
27
+ export interface BrowserJobResult {
28
+ protocolVersion: number;
29
+ jobId: string;
30
+ operation: 'playtest' | 'cover';
31
+ ok: boolean;
32
+ [key: string]: unknown;
33
+ }
34
+ export declare function runBrowserJob(contentGrant: string, operation: BrowserOperation, signal?: AbortSignal): Promise<BrowserJobResult>;
9
35
  export declare function startCLILogin(): Promise<{
10
36
  pollToken: string;
11
37
  url: string;
@@ -103,9 +129,13 @@ export interface CauldronServerConfig {
103
129
  tickRate: number;
104
130
  maxPlayers: number;
105
131
  }
106
- export declare function saveCauldronServerBundle(deckId: string, uploadId: string | null, serverConfig?: CauldronServerConfig): Promise<{
132
+ export interface CauldronServerBundleResult {
107
133
  deckId: string;
108
- } | null>;
134
+ version: string;
135
+ sha256: string;
136
+ sizeBytes: number;
137
+ }
138
+ export declare function saveCauldronServerBundle(deckId: string, uploadId: string | null, serverConfig?: CauldronServerConfig): Promise<CauldronServerBundleResult | null>;
109
139
  export interface WebDeckSource {
110
140
  deckId: string;
111
141
  archiveUrl: string;
package/dist/api.js CHANGED
@@ -3,7 +3,7 @@ import * as config from './config.js';
3
3
  // sandboxes (which also set CASTLE_TOKEN to a sandbox-scoped credential). Unset anywhere
4
4
  // else, so normal installs always talk to the real API.
5
5
  const API_HOST = process.env.CASTLE_API_URL || 'https://api.castle.xyz/graphql';
6
- export async function graphql(query, variables) {
6
+ export async function graphql(query, variables, options = {}) {
7
7
  const token = config.getToken();
8
8
  const headers = {
9
9
  'X-OS': 'cli',
@@ -13,14 +13,25 @@ export async function graphql(query, variables) {
13
13
  };
14
14
  if (token)
15
15
  headers['X-Auth-Token'] = token;
16
+ const timeoutSignal = AbortSignal.timeout(options.timeoutMs ?? 10_000);
17
+ const signal = options.signal
18
+ ? AbortSignal.any([timeoutSignal, options.signal])
19
+ : timeoutSignal;
16
20
  const res = await fetch(API_HOST, {
17
21
  method: 'POST',
18
22
  headers,
19
23
  body: JSON.stringify(variables ? { query, variables } : { query }),
20
- signal: AbortSignal.timeout(10000),
24
+ signal,
21
25
  });
22
26
  return res.json();
23
27
  }
28
+ export async function runBrowserJob(contentGrant, operation, signal) {
29
+ const data = await graphql(`mutation($contentGrant: String!, $operation: Json!) {
30
+ runBrowserJob(contentGrant: $contentGrant, operation: $operation)
31
+ }`, { contentGrant, operation }, { timeoutMs: 85_000, signal });
32
+ handleAPIError(data);
33
+ return pickData(data, 'runBrowserJob');
34
+ }
24
35
  // Castle masks every ClientError's message to "Unexpected error." and puts the
25
36
  // real one in `extensions.code` -- so the bare message is the same string for a
26
37
  // permissions failure, a missing deck, and a bad argument. Carry the code in the
@@ -213,9 +224,12 @@ export async function createCauldronServerBundleUploadConfig(deckId) {
213
224
  return pickData(data, 'createCauldronServerBundleUploadConfig');
214
225
  }
215
226
  export async function saveCauldronServerBundle(deckId, uploadId, serverConfig) {
216
- const data = await graphql(`mutation($deckId: ID!, $uploadId: ID, $config: Json) {
227
+ const data = await graphql(`mutation($deckId: ID!, $uploadId: String, $config: Json) {
217
228
  saveCauldronServerBundle(deckId: $deckId, uploadId: $uploadId, config: $config) {
218
229
  deckId
230
+ version
231
+ sha256
232
+ sizeBytes
219
233
  }
220
234
  }`, { deckId, uploadId, ...(serverConfig ? { config: serverConfig } : {}) });
221
235
  handleAPIError(data);
@@ -22,6 +22,8 @@
22
22
  import fs from "fs";
23
23
  import path from "path";
24
24
  import { createPlaytestBrowserManager } from "./native/playtest-browser.js";
25
+ import * as api from "./api.js";
26
+ import { contentGrantFromBrowserUrl } from "./native/playtest-remote.js";
25
27
  // The card is 5:7; this is the same fixed viewport the playtest tool uses, so a
26
28
  // deck laid out for one is laid out for the other.
27
29
  const VIEWPORT = { width: 500, height: 700 };
@@ -46,6 +48,10 @@ const CARD_SELECTOR = "#castle-card, [data-castle-card]";
46
48
  // Grab the deck's cover from `serveUrl` and write it to `<projectDir>/.castle`.
47
49
  // Never throws; a failure is reported, not raised.
48
50
  export async function captureCoverHeadless(opts) {
51
+ const remoteGrant = contentGrantFromBrowserUrl(opts.serveUrl);
52
+ if (remoteGrant) {
53
+ return captureCoverRemote(remoteGrant, opts.outPath);
54
+ }
49
55
  // A manager we made is a manager we must close. `withBrowser` deliberately
50
56
  // leaves the browser RUNNING so the next call reuses it -- right for the
51
57
  // agent, which holds one manager for its whole session, and fatal here:
@@ -84,6 +90,28 @@ export async function captureCoverHeadless(opts) {
84
90
  await manager.shutdown().catch(() => undefined);
85
91
  }
86
92
  }
93
+ async function captureCoverRemote(contentGrant, outPath) {
94
+ try {
95
+ const result = await api.runBrowserJob(contentGrant, { kind: 'cover' });
96
+ const pngBase64 = result.pngBase64;
97
+ if (result.protocolVersion !== 1 ||
98
+ result.operation !== 'cover' ||
99
+ !result.ok ||
100
+ typeof pngBase64 !== 'string') {
101
+ const error = typeof result.error === 'string' ? result.error : 'browser worker returned an invalid cover';
102
+ return { ok: false, error };
103
+ }
104
+ const png = Buffer.from(pngBase64, 'base64');
105
+ if (png.length === 0)
106
+ return { ok: false, error: 'browser worker returned an empty cover' };
107
+ fs.mkdirSync(path.dirname(outPath), { recursive: true });
108
+ fs.writeFileSync(outPath, png);
109
+ return { ok: true, outPath };
110
+ }
111
+ catch (error) {
112
+ return { ok: false, error: error instanceof Error ? error.message : String(error) };
113
+ }
114
+ }
87
115
  // Resolve with `work`, or with null if the budget runs out first. The loser is
88
116
  // abandoned rather than cancelled -- the shutdown in the caller's `finally` is
89
117
  // what actually stops the browser it was using.
@@ -0,0 +1,3 @@
1
+ import { type PlaytestExecutor } from './playtest.js';
2
+ export declare function contentGrantFromBrowserUrl(value: string): string | null;
3
+ export declare function createRemotePlaytestExecutor(browserContentUrl: () => string | null): PlaytestExecutor;
@@ -0,0 +1,113 @@
1
+ import * as api from '../api.js';
2
+ import { PLAYTEST_VIEWPORT, } from './playtest.js';
3
+ const CONTENT_HOST_RE = /^(?<grant>[a-z0-9-]{1,63})\.sandboxes(?:-staging)?\.castlexyz\.com$/;
4
+ function failed(input, error) {
5
+ return {
6
+ ok: false,
7
+ error,
8
+ viewport: PLAYTEST_VIEWPORT,
9
+ frames: [],
10
+ console: [],
11
+ diagnostics: {
12
+ rafTicks: 0,
13
+ wallMs: 0,
14
+ framesRequested: input.timeline.filter((event) => event.kind === 'screenshot').length,
15
+ framesCaptured: 0,
16
+ hidden: false,
17
+ },
18
+ };
19
+ }
20
+ export function contentGrantFromBrowserUrl(value) {
21
+ try {
22
+ const url = new URL(value);
23
+ if (url.protocol !== 'https:')
24
+ return null;
25
+ return CONTENT_HOST_RE.exec(url.hostname)?.groups?.grant ?? null;
26
+ }
27
+ catch {
28
+ return null;
29
+ }
30
+ }
31
+ function operationFromTimeline(input) {
32
+ const actions = [];
33
+ const screenshots = [];
34
+ const keyDown = new Map();
35
+ for (const event of input.timeline) {
36
+ if (event.kind === 'screenshot') {
37
+ screenshots.push(event.t);
38
+ }
39
+ else if (event.kind === 'keydown') {
40
+ const times = keyDown.get(event.key) ?? [];
41
+ times.push(event.t);
42
+ keyDown.set(event.key, times);
43
+ }
44
+ else if (event.kind === 'keyup') {
45
+ const times = keyDown.get(event.key);
46
+ const startedAt = times?.shift();
47
+ if (startedAt !== undefined) {
48
+ actions.push({
49
+ t: startedAt,
50
+ type: 'key',
51
+ key: event.key,
52
+ durationMs: event.t - startedAt,
53
+ });
54
+ }
55
+ }
56
+ else {
57
+ if (!('x' in event))
58
+ continue;
59
+ actions.push({
60
+ t: event.t,
61
+ type: event.kind === 'mousedown'
62
+ ? 'down'
63
+ : event.kind === 'mouseup'
64
+ ? 'up'
65
+ : 'move',
66
+ x: event.x,
67
+ y: event.y,
68
+ });
69
+ }
70
+ }
71
+ actions.sort((a, b) => a.t - b.t);
72
+ return { kind: 'playtest', durationMs: input.durationMs, actions, screenshots };
73
+ }
74
+ function validRemoteResult(result) {
75
+ return (result.protocolVersion === 1 &&
76
+ result.operation === 'playtest' &&
77
+ result.ok === true &&
78
+ result.viewport?.width === PLAYTEST_VIEWPORT.width &&
79
+ result.viewport?.height === PLAYTEST_VIEWPORT.height &&
80
+ Array.isArray(result.frames) &&
81
+ Array.isArray(result.console) &&
82
+ Boolean(result.diagnostics));
83
+ }
84
+ export function createRemotePlaytestExecutor(browserContentUrl) {
85
+ return {
86
+ async runSession(input) {
87
+ const contentUrl = browserContentUrl();
88
+ const grant = contentUrl ? contentGrantFromBrowserUrl(contentUrl) : null;
89
+ if (!grant)
90
+ return failed(input, 'the serve could not mint a browser content grant');
91
+ try {
92
+ const result = (await api.runBrowserJob(grant, operationFromTimeline(input), input.signal));
93
+ if (!result.ok)
94
+ return failed(input, result.error ?? 'browser worker failed');
95
+ if (!validRemoteResult(result))
96
+ return failed(input, 'browser worker returned an invalid result');
97
+ return {
98
+ ok: true,
99
+ viewport: result.viewport,
100
+ frames: result.frames.map((frame) => ({
101
+ t: frame.t,
102
+ png: Buffer.from(frame.pngBase64, 'base64'),
103
+ })),
104
+ console: result.console,
105
+ diagnostics: result.diagnostics,
106
+ };
107
+ }
108
+ catch (error) {
109
+ return failed(input, error instanceof Error ? error.message : String(error));
110
+ }
111
+ },
112
+ };
113
+ }
package/dist/save-deck.js CHANGED
@@ -122,12 +122,18 @@ async function publishServerBundle(projectDir, deckId) {
122
122
  console.log(`Server bundle size: ${(bundle.sizeBytes / 1024).toFixed(1)}KB`);
123
123
  const uploadConfig = await api.createCauldronServerBundleUploadConfig(deckId);
124
124
  await uploadPresignedFile(uploadConfig, new Blob([bundle.code], { type: 'application/javascript' }), 'application/javascript', 60_000, 'Server bundle upload');
125
- await api.saveCauldronServerBundle(deckId, uploadConfig.uploadId, {
125
+ const saved = await api.saveCauldronServerBundle(deckId, uploadConfig.uploadId, {
126
126
  tickRate: serverConfig.tickRate,
127
127
  maxPlayers: serverConfig.maxPlayers,
128
128
  });
129
+ // The server hashes what it actually stored. A mismatch means the bytes that
130
+ // will run in sessions are not the bytes we bundled.
131
+ if (saved && saved.sha256 !== bundle.sha256) {
132
+ throw new Error(`Published server bundle does not match what was built ` +
133
+ `(server ${saved.sha256}, local ${bundle.sha256}). The deck was not updated safely.`);
134
+ }
129
135
  writePublishedServerBundleState(projectDir, { deckId, sha256: bundle.sha256 });
130
- console.log(`Server bundle published (sha256 ${bundle.sha256}).`);
136
+ console.log(`Server bundle published${saved ? ` as ${saved.version}` : ''} (sha256 ${bundle.sha256}).`);
131
137
  }
132
138
  // Publish the deck's local cover, if it has one, and return the file id for the
133
139
  // card. The editor writes `preview.png` as you play (see the serve's cover
@@ -138,13 +144,24 @@ async function publishServerBundle(projectDir, deckId) {
138
144
  // The deck's own serve, if one is running -- the URL a headless cover capture
139
145
  // loads. No serve means no deck to photograph, which is a normal state (a save
140
146
  // from a script), not an error.
141
- function runningServeUrl(projectDir) {
147
+ async function runningServeUrl(projectDir) {
142
148
  try {
143
149
  const raw = fs.readFileSync(path.join(projectDir, '.castle', 'serve.json'), 'utf8');
144
150
  const parsed = JSON.parse(raw);
151
+ const port = parsed.port;
152
+ if (process.env.CASTLE_SANDBOX_ID && typeof port === 'number') {
153
+ try {
154
+ const response = await fetch(`http://localhost:${port}/__castle/browser-content-grant`, { signal: AbortSignal.timeout(2_000) });
155
+ const body = (await response.json());
156
+ if (response.ok && typeof body.url === 'string')
157
+ return body.url;
158
+ }
159
+ catch {
160
+ // Fall through to the existing best-effort local capture path.
161
+ }
162
+ }
145
163
  if (typeof parsed.contentPlayUrl === 'string')
146
164
  return parsed.contentPlayUrl;
147
- const port = parsed.port;
148
165
  return typeof port === 'number' ? `http://localhost:${port}` : null;
149
166
  }
150
167
  catch {
@@ -166,7 +183,7 @@ function runningServeUrl(projectDir) {
166
183
  // you never look at it, and nobody looks at an unattended capture. Writing to a
167
184
  // scratch file rather than over `preview.png` keeps that fallback intact.
168
185
  async function captureAutomaticCover(projectDir) {
169
- const serveUrl = runningServeUrl(projectDir);
186
+ const serveUrl = await runningServeUrl(projectDir);
170
187
  if (!serveUrl)
171
188
  return null;
172
189
  const outPath = path.join(projectDir, '.castle', 'headless-cover.png');
package/dist/serve.js CHANGED
@@ -81,11 +81,12 @@ function listenLocalContentServer(upstreamHost, upstreamPort, role, security, re
81
81
  });
82
82
  server.on('upgrade', (req, socket, head) => {
83
83
  const multiplayer = isDevMultiplayerUpgrade(req);
84
- if (!isViteClientUpgrade(req) && !multiplayer) {
84
+ const legacyContent = isLegacyContentSocketUpgrade(req);
85
+ if (!isViteClientUpgrade(req) && !multiplayer && !legacyContent) {
85
86
  socket.destroy();
86
87
  return;
87
88
  }
88
- if (multiplayer && !isSameOriginUpgrade(req)) {
89
+ if ((multiplayer || legacyContent) && !isSameOriginUpgrade(req)) {
89
90
  socket.destroy();
90
91
  return;
91
92
  }
@@ -162,6 +163,15 @@ function isDevMultiplayerUpgrade(req) {
162
163
  return false;
163
164
  }
164
165
  }
166
+ const LEGACY_CONTENT_WS_PATH = '/__castle/ws-legacy';
167
+ function isLegacyContentSocketUpgrade(req) {
168
+ try {
169
+ return new URL(req.url || '/', 'http://localhost').pathname === LEGACY_CONTENT_WS_PATH;
170
+ }
171
+ catch {
172
+ return false;
173
+ }
174
+ }
165
175
  async function startLocalContentServers(upstreamHost, upstreamPort, security, reserved) {
166
176
  const servers = [];
167
177
  const ports = {};
@@ -299,6 +309,23 @@ window.__castleShellOrigin=(function(){
299
309
  res.writeHead(403).end('untrusted host');
300
310
  return;
301
311
  }
312
+ if (reqPath === '/__castle/browser-content-grant') {
313
+ if (content || req.method !== 'GET') {
314
+ res.writeHead(403).end();
315
+ return;
316
+ }
317
+ const url = security.browserContentOrigin('play');
318
+ if (!url) {
319
+ res.writeHead(404).end();
320
+ return;
321
+ }
322
+ res.writeHead(200, {
323
+ 'content-type': 'application/json',
324
+ 'cache-control': 'no-store',
325
+ });
326
+ res.end(JSON.stringify({ url }));
327
+ return;
328
+ }
302
329
  if (reqPath === '/__castle/ws-ticket') {
303
330
  if (content || req.method !== 'POST') {
304
331
  res.writeHead(403).end();
@@ -317,8 +344,23 @@ window.__castleShellOrigin=(function(){
317
344
  res.end(JSON.stringify({ ticket: security.issueTicket(endpoint) }));
318
345
  return;
319
346
  }
347
+ // SDK <=0.4.16 discovers a direct socket here. Admit it through a
348
+ // one-use role-bound path so old editors keep saving while the play
349
+ // capability retains the same no-write boundary as the modern bridge.
350
+ if (reqPath === '/__castle/ws-port') {
351
+ if (!contentRole || req.method !== 'GET') {
352
+ res.writeHead(404).end();
353
+ return;
354
+ }
355
+ const ticket = security.issueLegacyContentTicket(contentRole);
356
+ res.writeHead(200, {
357
+ 'content-type': 'application/json',
358
+ 'cache-control': 'no-store',
359
+ });
360
+ res.end(JSON.stringify({ path: `${LEGACY_CONTENT_WS_PATH}?ticket=${ticket}` }));
361
+ return;
362
+ }
320
363
  if (reqPath === '/__castle/auth' ||
321
- reqPath === '/__castle/ws-port' ||
322
364
  reqPath === '/__castle/context') {
323
365
  res.writeHead(404).end();
324
366
  return;
@@ -461,6 +503,13 @@ const DEFAULT_PORT = 5757;
461
503
  // them (an import listing goes on to the browser's castle-www host and its
462
504
  // GraphQL scans); an unanswered id just sits in the map until this expires.
463
505
  const PENDING_REQUEST_TTL_MS = 30_000;
506
+ const BRIDGED_CONTENT_MESSAGES = new Set([
507
+ 'log',
508
+ 'screenshot_response',
509
+ 'write_file',
510
+ 'castle_command',
511
+ ]);
512
+ const LEGACY_CONTENT_MESSAGES = new Set([...BRIDGED_CONTENT_MESSAGES, 'ping']);
464
513
  function readServeJson(projectDir) {
465
514
  try {
466
515
  const raw = fs.readFileSync(path.join(projectDir, '.castle', 'serve.json'), 'utf8');
@@ -581,9 +630,11 @@ export async function serve(dir, options = {}) {
581
630
  // playtest tool, so this is free when that already pulled it, and every
582
631
  // failure is swallowed -- the capture re-detects and reports properly at the
583
632
  // point it actually matters.
584
- void import('./native/playtest-browser.js')
585
- .then((m) => m.createPlaytestBrowserManager().prewarm())
586
- .catch(() => undefined);
633
+ if (!process.env.CASTLE_SANDBOX_ID) {
634
+ void import('./native/playtest-browser.js')
635
+ .then((m) => m.createPlaytestBrowserManager().prewarm())
636
+ .catch(() => undefined);
637
+ }
587
638
  // Close stdin when not attached to a TTY so the process can be cleanly
588
639
  // backgrounded with `&` (otherwise stdin reads can block or hold the parent).
589
640
  if (!process.stdin.isTTY) {
@@ -690,6 +741,9 @@ export async function serve(dir, options = {}) {
690
741
  deckLabel: path.basename(projectDir),
691
742
  port,
692
743
  playtestServeUrl: security.localContentOrigin('play'),
744
+ browserContentUrl: process.env.CASTLE_SANDBOX_ID
745
+ ? () => security.browserContentOrigin('play')
746
+ : undefined,
693
747
  // Same effect as the WS server's own 'restart' branch below (invalidate
694
748
  // then tell every connected tab to reload), called directly in-process
695
749
  // instead of round-tripping through a WebSocket message -- this is what
@@ -916,29 +970,47 @@ async function serveDetached(projectDir, options) {
916
970
  }
917
971
  function startWSServer(projectDir, logFile, screenshotsDir, viteHolder, security, multiplayer) {
918
972
  // The control socket is upgraded directly on Vite's HTTP server. Browser
919
- // clients use the named path and a one-use ticket. The root path is accepted
973
+ // shell clients use the named path and a one-use ticket; pre-bridge SDKs use
974
+ // a separate ticket carrying their content role. The root path is accepted
920
975
  // only from loopback clients with no Origin so older CLI versions can read
921
976
  // wsPort from a new serve.json and continue to connect during rollout.
922
977
  const wss = new WebSocketServer({
923
978
  noServer: true,
924
979
  maxPayload: 12 * 1024 * 1024,
925
980
  });
981
+ const legacyRoles = new WeakMap();
926
982
  const handleUpgrade = (req, socket, head) => {
927
983
  const pathname = new URL(req.url || '/', 'http://localhost').pathname;
928
984
  const hasOrigin = Boolean(req.headers.origin);
929
985
  const isNamedPath = pathname === '/__castle/ws';
930
986
  const isLegacyCliPath = pathname === '/' && !hasOrigin;
931
- if (!isNamedPath && !isLegacyCliPath)
987
+ const isLegacyContentPath = pathname === LEGACY_CONTENT_WS_PATH;
988
+ if (!isNamedPath && !isLegacyCliPath && !isLegacyContentPath)
932
989
  return false;
933
990
  const loopback = req.socket.remoteAddress === '127.0.0.1' || req.socket.remoteAddress === '::1';
934
- const authorized = hasOrigin
935
- ? isNamedPath && isSameOriginUpgrade(req) && security.consumeTicket(req, 'serve')
936
- : loopback;
991
+ let legacyRole = null;
992
+ let authorized;
993
+ if (isLegacyContentPath) {
994
+ legacyRole = security.consumeLegacyContentTicket(req);
995
+ const assertedRole = security.verifyContentRequest(req);
996
+ authorized =
997
+ legacyRole !== null &&
998
+ (assertedRole === legacyRole || (assertedRole === null && isSameOriginUpgrade(req)));
999
+ }
1000
+ else {
1001
+ authorized = hasOrigin
1002
+ ? isNamedPath && isSameOriginUpgrade(req) && security.consumeTicket(req, 'serve')
1003
+ : loopback;
1004
+ }
937
1005
  if (!authorized) {
938
1006
  socket.destroy();
939
1007
  return true;
940
1008
  }
941
- wss.handleUpgrade(req, socket, head, (ws) => wss.emit('connection', ws, req));
1009
+ wss.handleUpgrade(req, socket, head, (ws) => {
1010
+ if (legacyRole)
1011
+ legacyRoles.set(ws, legacyRole);
1012
+ wss.emit('connection', ws, req);
1013
+ });
942
1014
  return true;
943
1015
  };
944
1016
  const clients = new Set();
@@ -963,6 +1035,7 @@ function startWSServer(projectDir, logFile, screenshotsDir, viteHolder, security
963
1035
  wss.on('connection', (ws, req) => {
964
1036
  clients.add(ws);
965
1037
  const multiplayerUrl = devMultiplayerUrl(req);
1038
+ const legacyRole = legacyRoles.get(ws) ?? null;
966
1039
  ws.on('message', (raw) => {
967
1040
  try {
968
1041
  const text = Array.isArray(raw)
@@ -974,6 +1047,8 @@ function startWSServer(projectDir, logFile, screenshotsDir, viteHolder, security
974
1047
  let bridgeRole = null;
975
1048
  let bridgeContentOrigin = null;
976
1049
  if (msg.type === 'deck_bridge') {
1050
+ if (legacyRole)
1051
+ return;
977
1052
  if ((msg.role !== 'edit' && msg.role !== 'play') ||
978
1053
  !msg.message ||
979
1054
  typeof msg.message !== 'object')
@@ -981,10 +1056,12 @@ function startWSServer(projectDir, logFile, screenshotsDir, viteHolder, security
981
1056
  bridgeRole = msg.role;
982
1057
  bridgeContentOrigin = trustedBridgeContentOrigin(security, req, bridgeRole, msg.contentOrigin);
983
1058
  msg = msg.message;
984
- const allowed = new Set(['log', 'screenshot_response', 'write_file', 'castle_command']);
985
- if (!allowed.has(String(msg.type)))
1059
+ if (!BRIDGED_CONTENT_MESSAGES.has(String(msg.type)))
986
1060
  return;
987
1061
  }
1062
+ else if (legacyRole && !LEGACY_CONTENT_MESSAGES.has(String(msg.type))) {
1063
+ return;
1064
+ }
988
1065
  // Liveness. A client asks so it can tell a live connection from one that
989
1066
  // died without a close -- the state a sleeping laptop or a dropped
990
1067
  // network leaves behind, which `readyState` reports as OPEN forever.
@@ -1088,7 +1165,7 @@ function startWSServer(projectDir, logFile, screenshotsDir, viteHolder, security
1088
1165
  }
1089
1166
  }
1090
1167
  if (msg.type === 'write_file') {
1091
- if (bridgeRole === 'play') {
1168
+ if ((bridgeRole ?? legacyRole) === 'play') {
1092
1169
  ws.send(JSON.stringify({
1093
1170
  type: 'write_file_response',
1094
1171
  requestId: msg.requestId,
@@ -25,7 +25,11 @@ export declare class ServeSecurity {
25
25
  authorizeHttp(req: http.IncomingMessage): boolean;
26
26
  rejectHttpAuth(res: http.ServerResponse): void;
27
27
  issueTicket(endpoint: SocketEndpoint): string;
28
+ /** One-use admission for an SDK that predates the shell's MessagePort bridge. */
29
+ issueLegacyContentTicket(role: ContentRole): string;
28
30
  consumeTicket(req: http.IncomingMessage, endpoint: SocketEndpoint): boolean;
31
+ /** Consume and recover the edit/play role bound to a legacy content ticket. */
32
+ consumeLegacyContentTicket(req: http.IncomingMessage): ContentRole | null;
29
33
  private pruneTickets;
30
34
  shellBootstrap(req: http.IncomingMessage): string;
31
35
  contentOrigins(req: http.IncomingMessage): {
@@ -33,6 +37,8 @@ export declare class ServeSecurity {
33
37
  playOrigin: string;
34
38
  };
35
39
  localContentOrigin(role: ContentRole): string;
40
+ /** A short-lived play URL for one shared-browser admission attempt. */
41
+ browserContentOrigin(role?: ContentRole): string | null;
36
42
  localContentProxyHeaders(role: ContentRole): Record<string, string>;
37
43
  verifyContentRequest(req: http.IncomingMessage): ContentRole | null;
38
44
  compatibilityContentRole(req: http.IncomingMessage): ContentRole | null;
@@ -5,6 +5,7 @@ const CROCKFORD = '0123456789abcdefghjkmnpqrstvwxyz';
5
5
  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})$/;
6
6
  const MAX_GRANT_SECONDS = 12 * 60 * 60;
7
7
  const GRANT_CLOCK_SKEW_SECONDS = 60;
8
+ const BROWSER_GRANT_SECONDS = 3 * 60;
8
9
  export const MOBILE_HOST_PROTOCOL = '2';
9
10
  function base32Lower(bytes) {
10
11
  let bits = 0;
@@ -87,6 +88,17 @@ export class ServeSecurity {
87
88
  this.tickets.set(ticket, { endpoint, expiresAt: Date.now() + 30_000 });
88
89
  return ticket;
89
90
  }
91
+ /** One-use admission for an SDK that predates the shell's MessagePort bridge. */
92
+ issueLegacyContentTicket(role) {
93
+ this.pruneTickets();
94
+ const ticket = randomBytes(16).toString('base64url');
95
+ this.tickets.set(ticket, {
96
+ endpoint: 'legacy-content',
97
+ role,
98
+ expiresAt: Date.now() + 30_000,
99
+ });
100
+ return ticket;
101
+ }
90
102
  consumeTicket(req, endpoint) {
91
103
  this.pruneTickets();
92
104
  let ticket = '';
@@ -102,6 +114,26 @@ export class ServeSecurity {
102
114
  this.tickets.delete(ticket);
103
115
  return record.endpoint === endpoint && record.expiresAt > Date.now();
104
116
  }
117
+ /** Consume and recover the edit/play role bound to a legacy content ticket. */
118
+ consumeLegacyContentTicket(req) {
119
+ this.pruneTickets();
120
+ let ticket = '';
121
+ try {
122
+ ticket = new URL(req.url || '/', 'http://localhost').searchParams.get('ticket') || '';
123
+ }
124
+ catch {
125
+ return null;
126
+ }
127
+ const record = this.tickets.get(ticket);
128
+ if (!record)
129
+ return null;
130
+ this.tickets.delete(ticket);
131
+ return record.endpoint === 'legacy-content' &&
132
+ (record.role === 'edit' || record.role === 'play') &&
133
+ record.expiresAt > Date.now()
134
+ ? record.role
135
+ : null;
136
+ }
105
137
  pruneTickets() {
106
138
  const now = Date.now();
107
139
  for (const [ticket, record] of this.tickets) {
@@ -209,6 +241,18 @@ window.fetch=function(input,init){
209
241
  throw new Error('local content ports are not configured');
210
242
  return `http://127.0.0.1:${port}`;
211
243
  }
244
+ /** A short-lived play URL for one shared-browser admission attempt. */
245
+ browserContentOrigin(role = 'play') {
246
+ const sandboxId = process.env.CASTLE_SANDBOX_ID;
247
+ if (!sandboxId || !/^[a-z0-9]{14}$/.test(sandboxId))
248
+ return null;
249
+ const env = process.env.CASTLE_SANDBOX_ENV === 'staging' ? 'staging' : 'prod';
250
+ const domain = env === 'staging'
251
+ ? 'sandboxes-staging.castlexyz.com'
252
+ : 'sandboxes.castlexyz.com';
253
+ const expiresAtSeconds = Math.floor(Date.now() / 1000) + BROWSER_GRANT_SECONDS;
254
+ return `https://${this.mintContentLabel(role, sandboxId, expiresAtSeconds)}.${domain}`;
255
+ }
212
256
  localContentProxyHeaders(role) {
213
257
  return {
214
258
  'x-castle-content-role': role,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "castle-web-cli",
3
- "version": "0.4.150",
3
+ "version": "0.4.152",
4
4
  "type": "module",
5
5
  "bin": {
6
6
  "castle-web": "./dist/index.js"