castle-web-cli 0.4.147 → 0.4.149

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.
@@ -30,6 +30,7 @@ const COMMAND_NAMES = [
30
30
  "portal.open",
31
31
  "portal.prefetch",
32
32
  "haptics.play",
33
+ "multiplayer.getSession",
33
34
  ];
34
35
  // Platform/capability commands: NOT serviced by graphqlFetch. They're dispatched
35
36
  // to the host's optional platformHandler (mobile renders native UI; web shows an
@@ -110,6 +111,8 @@ function runCommand(ctx, command, params, caps) {
110
111
  return timeGetServerTime(gql);
111
112
  case "pass.has":
112
113
  return passHas(ctx, params, caps);
114
+ case "multiplayer.getSession":
115
+ return multiplayerGetSession(ctx, params, caps);
113
116
  // Platform commands are handled above; listed here to keep the switch
114
117
  // exhaustive over CommandName.
115
118
  case "pass.offer":
@@ -119,6 +122,33 @@ function runCommand(ctx, command, params, caps) {
119
122
  return runPlatformCommand(ctx, command, params, caps);
120
123
  }
121
124
  }
125
+ async function multiplayerGetSession(ctx, params, caps) {
126
+ const mode = asMultiplayerMode(params.mode);
127
+ const request = {
128
+ mode,
129
+ key: mode === "named"
130
+ ? asString(params.key, "key", "multiplayer.getSession")
131
+ : null,
132
+ };
133
+ if (caps.getMultiplayerSession) {
134
+ return caps.getMultiplayerSession(request, ctx);
135
+ }
136
+ const deckId = requireDeckId(ctx, "multiplayer.getSession");
137
+ const data = await graphql(caps.graphqlFetch, CAULDRON_MULTIPLAYER_SESSION_QUERY, { deckId, mode, key: request.key ?? null, partyId: ctx.partyId ?? null }, "multiplayer.getSession");
138
+ return multiplayerSessionResult(data.getCauldronMultiplayerSession);
139
+ }
140
+ function multiplayerSessionResult(value) {
141
+ const sessionId = asOptionalString(value?.sessionId);
142
+ if (value?.isSingleUserSession === true) {
143
+ return { status: "solo", url: null, nonce: null, sessionId };
144
+ }
145
+ const url = asOptionalString(value?.url);
146
+ const nonce = asOptionalString(value?.nonce);
147
+ if (!url || !nonce) {
148
+ return { status: "unavailable", url: null, nonce: null, sessionId };
149
+ }
150
+ return { status: "ok", url, nonce, sessionId };
151
+ }
122
152
  // Dispatch a platform/capability command to the host's platformHandler. No
123
153
  // handler → the command's normalized "unavailable" outcome (a SUCCESS, not an
124
154
  // error: a deck on a host without this capability still gets one uniform
@@ -534,6 +564,11 @@ function asOptionalString(value) {
534
564
  function asOptionalNumber(value) {
535
565
  return typeof value === "number" && Number.isFinite(value) ? value : null;
536
566
  }
567
+ function asMultiplayerMode(value) {
568
+ if (value === "named" || value === "party" || value === "public")
569
+ return value;
570
+ throw new HostCommandError("INVALID_ARGUMENT", "Castle command multiplayer.getSession requires mode.", "multiplayer.getSession");
571
+ }
537
572
  // GraphQL hands numeric fields back as numbers or as strings depending on the
538
573
  // scalar, so leaderboard payload shaping accepts both.
539
574
  function asNumberish(value) {
@@ -780,3 +815,23 @@ const SERVER_TIME_QUERY = `
780
815
  }
781
816
  }
782
817
  `;
818
+ const CAULDRON_MULTIPLAYER_SESSION_QUERY = `
819
+ query CastleCauldronMultiplayerSession(
820
+ $deckId: ID!
821
+ $mode: String!
822
+ $key: String
823
+ $partyId: ID
824
+ ) {
825
+ getCauldronMultiplayerSession(
826
+ deckId: $deckId
827
+ mode: $mode
828
+ key: $key
829
+ partyId: $partyId
830
+ ) {
831
+ sessionId
832
+ isSingleUserSession
833
+ url
834
+ nonce
835
+ }
836
+ }
837
+ `;
package/dist/init.js CHANGED
@@ -46,7 +46,7 @@ export const BARE_DOCS_KIT = 'blank';
46
46
  // Registry version of castle-web-sdk to inject when scaffolding from a
47
47
  // globally-installed castle-web (not from inside the workspace). Bumped
48
48
  // alongside cli/sdk version bumps.
49
- const PUBLISHED_SDK_VERSION = '0.4.18';
49
+ const PUBLISHED_SDK_VERSION = '0.4.19';
50
50
  // The account the first-party kits are (to be) published under, so a kit
51
51
  // imported from the CLI's copy is named the same as one fetched from the server.
52
52
  const KIT_AUTHOR = 'castle';
package/dist/serve.js CHANGED
@@ -17,7 +17,7 @@ import { FORKS_DIR, ownForkFile, splitImportRel } from './forks.js';
17
17
  import * as config from './config.js';
18
18
  import { graphql as castleGraphql } from './api.js';
19
19
  import { executeCommand } from './castle-host/host.js';
20
- import { ServeSecurity, } from './serveSecurity.js';
20
+ import { ServeSecurity } from './serveSecurity.js';
21
21
  import { isSameOriginUpgrade } from './wsOrigin.js';
22
22
  // The log is a tail, not an archive: append, and once it passes the cap drop
23
23
  // whole lines off the front until it is back under.
@@ -205,7 +205,7 @@ export function isAllowedShellHost(hostHeader, configuredHost) {
205
205
  if (host.endsWith('.local') || host.endsWith('.ts.net'))
206
206
  return true;
207
207
  const configured = configuredHost ? hostnameFromHeader(configuredHost) : '';
208
- return configured !== '' && configured !== '0.0.0.0' && configured !== '::' && host === configured;
208
+ return (configured !== '' && configured !== '0.0.0.0' && configured !== '::' && host === configured);
209
209
  }
210
210
  const EDIT_CONTENT_READ_ENDPOINTS = new Set([
211
211
  '/__castle/files/raw',
@@ -243,6 +243,21 @@ window.__castleShellOrigin=(function(){
243
243
  if(h.endsWith('.sandboxes.castlexyz.com'))return 'https://'+p+'-'+sid+'.sandboxes.castle.xyz';
244
244
  return null;
245
245
  })();
246
+ (function(){
247
+ var role=new URLSearchParams(location.search).get('edit')==='0'?'play':'edit';
248
+ var target=window.__castleShellOrigin||'*';
249
+ var announce=function(){
250
+ if(window.parent===window)return;
251
+ window.parent.postMessage({type:'castle-content-frame-ready',role:role},target);
252
+ };
253
+ window.addEventListener('message',function(event){
254
+ var d=event&&event.data;
255
+ if(event.source!==window.parent||!d||d.type!=='castle-request-content-frame-ready')return;
256
+ if(window.__castleShellOrigin&&event.origin!==window.__castleShellOrigin)return;
257
+ announce();
258
+ });
259
+ window.addEventListener('load',function(){setTimeout(announce,0);},{once:true});
260
+ })();
246
261
  </script>\n ${CONSOLE_CAPTURE}`);
247
262
  },
248
263
  },
@@ -251,8 +266,9 @@ window.__castleShellOrigin=(function(){
251
266
  const reqPath = (req.url || '/').split('?')[0];
252
267
  const trustedSurface = req.headers['x-castle-sandbox-surface'];
253
268
  const verifiedRole = security.verifyContentRequest(req);
254
- const content = trustedSurface === 'content' || verifiedRole !== null;
255
- if (content && !verifiedRole) {
269
+ const contentRole = verifiedRole ?? security.compatibilityContentRole(req);
270
+ const content = trustedSurface === 'content' || contentRole !== null;
271
+ if (content && !contentRole) {
256
272
  res.writeHead(403).end('invalid content capability');
257
273
  return;
258
274
  }
@@ -274,21 +290,24 @@ window.__castleShellOrigin=(function(){
274
290
  res.end(JSON.stringify({ ticket: security.issueTicket(endpoint) }));
275
291
  return;
276
292
  }
277
- if (reqPath === '/__castle/auth' || reqPath === '/__castle/ws-port' || reqPath === '/__castle/context') {
293
+ if (reqPath === '/__castle/auth' ||
294
+ reqPath === '/__castle/ws-port' ||
295
+ reqPath === '/__castle/context') {
278
296
  res.writeHead(404).end();
279
297
  return;
280
298
  }
281
299
  if (content) {
282
300
  if (reqPath === '/')
283
301
  req.url = `/index.html${req.url?.includes('?') ? req.url.slice(req.url.indexOf('?')) : ''}`;
284
- const allowedFilesRequest = isAllowedContentFilesRequest(verifiedRole, req.method, reqPath);
302
+ const allowedFilesRequest = isAllowedContentFilesRequest(contentRole, req.method, reqPath);
285
303
  const allowedVendor = reqPath.startsWith('/__castle/vendor/');
286
304
  const allowedFavicon = FAVICON_FILES.some((name) => reqPath === `/${name}`);
287
305
  if (reqPath.startsWith('/__castle/') && !allowedFilesRequest && !allowedVendor) {
288
306
  res.writeHead(403).end('content capability does not allow this endpoint');
289
307
  return;
290
308
  }
291
- if ((allowedFilesRequest || allowedVendor || allowedFavicon) && ideServer.handleHttpRequest(req, res, reqPath))
309
+ if ((allowedFilesRequest || allowedVendor || allowedFavicon) &&
310
+ ideServer.handleHttpRequest(req, res, reqPath))
292
311
  return;
293
312
  next();
294
313
  return;
@@ -316,29 +335,32 @@ window.__castleShellOrigin=(function(){
316
335
  },
317
336
  };
318
337
  }
319
- // The dev author's username, fetched once (config stores token+userId but not
320
- // username). Cached for the serve lifetime so User.getCurrent works in dev.
321
- let cachedDevUsername;
322
- async function devUsername() {
323
- if (cachedDevUsername !== undefined)
324
- return cachedDevUsername;
338
+ // The serve's own user, fetched once and cached for the serve lifetime so
339
+ // User.getCurrent works in dev. Config may carry only a token: a sandbox
340
+ // starts the serve with CASTLE_TOKEN alone and no config.json, so the userId
341
+ // has to come from `me` there too, not just the username.
342
+ let cachedDevMe;
343
+ async function devMe() {
344
+ if (cachedDevMe !== undefined)
345
+ return cachedDevMe;
325
346
  try {
326
- const res = await castleGraphql('query { me { username } }', {});
347
+ const res = await castleGraphql('query { me { userId username } }', {});
327
348
  const me = res.data?.me;
328
- cachedDevUsername = me?.username ?? null;
349
+ cachedDevMe = { userId: me?.userId ?? null, username: me?.username ?? null };
329
350
  }
330
351
  catch {
331
- cachedDevUsername = null;
352
+ cachedDevMe = { userId: null, username: null };
332
353
  }
333
- return cachedDevUsername;
354
+ return cachedDevMe;
334
355
  }
335
356
  async function devHostContext(projectDir) {
336
357
  const ctx = readDeckContext(projectDir);
358
+ const me = await devMe();
337
359
  return {
338
360
  deckId: ctx.deckId ?? null,
339
361
  sessionId: null,
340
- userId: config.getUserId(),
341
- username: await devUsername(),
362
+ userId: config.getUserId() ?? me.userId,
363
+ username: me.username,
342
364
  };
343
365
  }
344
366
  async function handleCastleCommand(ws, projectDir, broadcast, requestId, command, params) {
@@ -617,7 +639,17 @@ export async function serve(dir, options = {}) {
617
639
  fs: {
618
640
  strict: true,
619
641
  allow: [projectDir],
620
- deny: ['.env', '.env.*', '*.pem', '*.key', '*.crt', '.castle', '.castle/**', '.git', '.git/**'],
642
+ deny: [
643
+ '.env',
644
+ '.env.*',
645
+ '*.pem',
646
+ '*.key',
647
+ '*.crt',
648
+ '.castle',
649
+ '.castle/**',
650
+ '.git',
651
+ '.git/**',
652
+ ],
621
653
  },
622
654
  },
623
655
  logLevel: 'info',
@@ -845,12 +877,7 @@ function startWSServer(port, projectDir, logFile, screenshotsDir, viteHolder, se
845
877
  return;
846
878
  bridgeRole = msg.role;
847
879
  msg = msg.message;
848
- const allowed = new Set([
849
- 'log',
850
- 'screenshot_response',
851
- 'write_file',
852
- 'castle_command',
853
- ]);
880
+ const allowed = new Set(['log', 'screenshot_response', 'write_file', 'castle_command']);
854
881
  if (!allowed.has(String(msg.type)))
855
882
  return;
856
883
  }
@@ -2,6 +2,7 @@ import type * as http from 'http';
2
2
  export type ContentRole = 'edit' | 'play';
3
3
  export type SocketEndpoint = 'serve' | 'pty' | 'agent';
4
4
  export type LocalContentPorts = Record<ContentRole, number>;
5
+ export declare const MOBILE_HOST_PROTOCOL = "2";
5
6
  export declare function mintContentGrantLabel(grant: {
6
7
  role: ContentRole;
7
8
  publicPort: number;
@@ -30,7 +31,9 @@ export declare class ServeSecurity {
30
31
  localContentOrigin(role: ContentRole): string;
31
32
  localContentProxyHeaders(role: ContentRole): Record<string, string>;
32
33
  verifyContentRequest(req: http.IncomingMessage): ContentRole | null;
34
+ compatibilityContentRole(req: http.IncomingMessage): ContentRole | null;
33
35
  shellOrigin(req: http.IncomingMessage): string;
34
36
  private mintContentLabel;
37
+ private requestsIsolatedContentOrigins;
35
38
  private contentMac;
36
39
  }
@@ -3,6 +3,7 @@ const CROCKFORD = '0123456789abcdefghjkmnpqrstvwxyz';
3
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
4
  const MAX_GRANT_SECONDS = 12 * 60 * 60;
5
5
  const GRANT_CLOCK_SKEW_SECONDS = 60;
6
+ export const MOBILE_HOST_PROTOCOL = '2';
6
7
  function base32Lower(bytes) {
7
8
  let bits = 0;
8
9
  let value = 0;
@@ -135,12 +136,11 @@ window.fetch=function(input,init){
135
136
  contentOrigins(req) {
136
137
  const host = hostWithoutPort(req.headers.host || 'localhost');
137
138
  const cloud = host.match(/^\d+-([a-z0-9]{14})\.(sandboxes(?:-staging)?\.castle\.xyz)$/);
138
- // Compatibility rollback: the released iOS WebView only permits castle.xyz
139
- // origins, so a sandboxes.castlexyz.com iframe is rejected before the deck
140
- // can load. Keep the isolated-origin implementation available for explicit
141
- // staging/device testing, but make ordinary cloud images use the existing
142
- // shell origin until a compatible native release is in production.
143
- if (cloud && process.env.CASTLE_ISOLATED_CONTENT_ORIGINS !== '1') {
139
+ // Released clients that predate protocol 2 reject the separate registrable
140
+ // content domain at the native WebView layer. Missing and unknown protocol
141
+ // values therefore stay on the compatibility origin forever; only an
142
+ // explicit client capability (or the staging override) opts into isolation.
143
+ if (cloud && !this.requestsIsolatedContentOrigins(req)) {
144
144
  const origin = requestOrigin(req);
145
145
  return { editOrigin: origin, playOrigin: origin };
146
146
  }
@@ -201,6 +201,47 @@ window.fetch=function(input,init){
201
201
  const expected = this.contentMac(role, publicPort, match[3], expiresAtSeconds, match[5]);
202
202
  return safeEqual(expected, match[6]) ? role : null;
203
203
  }
204
+ compatibilityContentRole(req) {
205
+ if (process.env.CASTLE_ISOLATED_CONTENT_ORIGINS === '1')
206
+ return null;
207
+ const host = hostWithoutPort(req.headers.host || '');
208
+ if (!/^\d+-[a-z0-9]{14}\.sandboxes(?:-staging)?\.castle\.xyz$/.test(host)) {
209
+ return null;
210
+ }
211
+ let requestUrl;
212
+ try {
213
+ requestUrl = new URL(req.url || '/', requestOrigin(req));
214
+ }
215
+ catch {
216
+ return null;
217
+ }
218
+ // `/` and the IDE bundle belong to the trusted shell. Everything else is
219
+ // deck content in compatibility mode, where released mobile clients require
220
+ // both frames to stay on the castle.xyz shell origin.
221
+ if (requestUrl.pathname === '/' || requestUrl.pathname.startsWith('/__castle/ide/')) {
222
+ return null;
223
+ }
224
+ if (requestUrl.pathname === '/index.html') {
225
+ return requestUrl.searchParams.get('edit') === '0' ? 'play' : 'edit';
226
+ }
227
+ // Browser fetches made by a frame retain the document URL as their same-origin
228
+ // referrer. Use it to preserve the edit-only file-read boundary. Static deck
229
+ // assets do not need that capability and can safely use the play role fallback.
230
+ const referer = req.headers.referer;
231
+ if (typeof referer === 'string') {
232
+ try {
233
+ const referrerUrl = new URL(referer);
234
+ if (referrerUrl.origin === requestOrigin(req) &&
235
+ referrerUrl.pathname === '/index.html') {
236
+ return referrerUrl.searchParams.get('edit') === '0' ? 'play' : 'edit';
237
+ }
238
+ }
239
+ catch {
240
+ // Malformed referrers never receive edit privileges.
241
+ }
242
+ }
243
+ return requestUrl.pathname.startsWith('/__castle/') ? null : 'play';
244
+ }
204
245
  shellOrigin(req) {
205
246
  return requestOrigin(req);
206
247
  }
@@ -213,6 +254,17 @@ window.fetch=function(input,init){
213
254
  serveNonce: this.serveNonce,
214
255
  }, this.signingKey);
215
256
  }
257
+ requestsIsolatedContentOrigins(req) {
258
+ if (process.env.CASTLE_ISOLATED_CONTENT_ORIGINS === '1')
259
+ return true;
260
+ try {
261
+ return (new URL(req.url || '/', requestOrigin(req)).searchParams.get('mobileHostProtocol') ===
262
+ MOBILE_HOST_PROTOCOL);
263
+ }
264
+ catch {
265
+ return false;
266
+ }
267
+ }
216
268
  contentMac(role, publicPort, sandboxId, expiresAtSeconds, serveNonce) {
217
269
  return mintContentGrantLabel({ role, publicPort, sandboxId, expiresAtSeconds, serveNonce }, this.signingKey)
218
270
  .split('-')