castle-web-cli 0.4.148 → 0.4.150

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.
Files changed (41) hide show
  1. package/dist/api.d.ts +14 -0
  2. package/dist/api.js +18 -0
  3. package/dist/castle-host/host.d.ts +17 -0
  4. package/dist/castle-host/host.js +58 -0
  5. package/dist/castleJson.d.ts +15 -0
  6. package/dist/castleJson.js +36 -0
  7. package/dist/devSessionChild.d.ts +1 -0
  8. package/dist/devSessionChild.js +129 -0
  9. package/dist/devSessionServer.d.ts +19 -0
  10. package/dist/devSessionServer.js +511 -0
  11. package/dist/index.js +8 -8
  12. package/dist/init.js +10 -2
  13. package/dist/list-decks.js +7 -6
  14. package/dist/preview.d.ts +1 -1
  15. package/dist/preview.js +4 -2
  16. package/dist/save-deck.js +63 -14
  17. package/dist/serve.js +269 -108
  18. package/dist/serveSecurity.d.ts +7 -1
  19. package/dist/serveSecurity.js +65 -16
  20. package/dist/serverBundle.d.ts +8 -0
  21. package/dist/serverBundle.js +82 -0
  22. package/dist/shell/assets/{index-CL9TuLXb.js → index-Dlhc3eZW.js} +42 -42
  23. package/dist/shell/assets/index-DwezawBs.css +1 -0
  24. package/dist/shell/index.html +2 -2
  25. package/kits/blank/castle.json +5 -2
  26. package/kits/physics-2d/behaviors/Collider.jsx +1 -2
  27. package/kits/physics-2d/behaviors/Joints.jsx +1 -1
  28. package/kits/physics-2d/castle.json +1 -1
  29. package/kits/physics-2d/editors/BlueprintLibrary.jsx +33 -3
  30. package/kits/physics-2d/editors/SceneEditor.jsx +319 -140
  31. package/kits/physics-2d/editors/SingleEditor.jsx +6 -0
  32. package/kits/physics-2d/engine/blueprint.js +106 -14
  33. package/kits/physics-2d/engine/scene.js +9 -2
  34. package/kits/physics-2d/engine/ui.jsx +30 -2
  35. package/kits/physics-2d/engine/ui.module.css +59 -0
  36. package/kits/physics-3d/castle.json +1 -1
  37. package/kits/physics-3d/engine3d/PxModelEditor.jsx +29 -13
  38. package/kits/physics-3d/engine3d/Scene3DEditor.jsx +26 -7
  39. package/kits/physics-3d/engine3d/editorChrome.jsx +26 -1
  40. package/package.json +1 -1
  41. package/dist/shell/assets/index-DN8HQBnW.css +0 -1
@@ -1,8 +1,11 @@
1
1
  import { createHmac, randomBytes, timingSafeEqual } from 'crypto';
2
+ export const SERVE_AUTH_FAILURE_HEADER = 'x-castle-serve-auth';
3
+ export const SERVE_AUTH_FAILURE_VALUE = 'invalid';
2
4
  const CROCKFORD = '0123456789abcdefghjkmnpqrstvwxyz';
3
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})$/;
4
6
  const MAX_GRANT_SECONDS = 12 * 60 * 60;
5
7
  const GRANT_CLOCK_SKEW_SECONDS = 60;
8
+ export const MOBILE_HOST_PROTOCOL = '2';
6
9
  function base32Lower(bytes) {
7
10
  let bits = 0;
8
11
  let value = 0;
@@ -49,23 +52,35 @@ export function mintContentGrantLabel(grant, signingKey) {
49
52
  }
50
53
  export class ServeSecurity {
51
54
  publicPort;
52
- localContentPorts;
53
55
  serveToken = randomBytes(32).toString('base64url');
54
56
  contentProxyToken = randomBytes(32).toString('base64url');
55
57
  signingKey = process.env.CASTLE_AGENT_TOKEN || randomBytes(32).toString('base64url');
56
58
  serveNonce = base32Lower(randomBytes(8));
57
59
  tickets = new Map();
58
- constructor(publicPort, localContentPorts = {
59
- edit: publicPort + 2,
60
- play: publicPort + 3,
61
- }) {
60
+ localContentPorts;
61
+ constructor(publicPort, localContentPorts) {
62
62
  this.publicPort = publicPort;
63
- this.localContentPorts = localContentPorts;
63
+ this.localContentPorts = localContentPorts ?? null;
64
+ }
65
+ setLocalContentPorts(ports) {
66
+ if (this.localContentPorts)
67
+ throw new Error('local content ports are already configured');
68
+ if (ports.edit === ports.play)
69
+ throw new Error('edit and play content ports must be distinct');
70
+ this.localContentPorts = ports;
64
71
  }
65
72
  authorizeHttp(req) {
66
73
  const value = req.headers['x-castle-serve-token'];
67
74
  return typeof value === 'string' && safeEqual(value, this.serveToken);
68
75
  }
76
+ rejectHttpAuth(res) {
77
+ res
78
+ .writeHead(403, {
79
+ [SERVE_AUTH_FAILURE_HEADER]: SERVE_AUTH_FAILURE_VALUE,
80
+ 'cache-control': 'no-store',
81
+ })
82
+ .end();
83
+ }
69
84
  issueTicket(endpoint) {
70
85
  this.pruneTickets();
71
86
  const ticket = randomBytes(16).toString('base64url');
@@ -118,6 +133,25 @@ window.__CASTLE_SERVE_TOKEN__=${JSON.stringify(this.serveToken)};
118
133
  window.__CASTLE_CONTENT_ORIGINS__=${JSON.stringify({ edit: editOrigin, play: playOrigin })};
119
134
  window.__CASTLE_HOST_ORIGIN__=${JSON.stringify(hostOrigin)};
120
135
  var nativeFetch=window.fetch.bind(window);
136
+ var authReloadKey='castle:serve-auth-reload';
137
+ var authReloadScheduled=false;
138
+ var authReloadStorage=true;
139
+ try {
140
+ var previousAuthReload=sessionStorage.getItem(authReloadKey);
141
+ if(previousAuthReload&&previousAuthReload!==window.__CASTLE_SERVE_TOKEN__){
142
+ sessionStorage.removeItem(authReloadKey);
143
+ }
144
+ }catch(e){authReloadStorage=false;}
145
+ function recoverStaleServeAuth(response){
146
+ if(response.headers.get(${JSON.stringify(SERVE_AUTH_FAILURE_HEADER)})!==${JSON.stringify(SERVE_AUTH_FAILURE_VALUE)})return;
147
+ if(authReloadScheduled||!authReloadStorage)return;
148
+ try {
149
+ if(sessionStorage.getItem(authReloadKey)===window.__CASTLE_SERVE_TOKEN__)return;
150
+ sessionStorage.setItem(authReloadKey,window.__CASTLE_SERVE_TOKEN__);
151
+ }catch(e){authReloadStorage=false;return;}
152
+ authReloadScheduled=true;
153
+ window.location.reload();
154
+ }
121
155
  window.fetch=function(input,init){
122
156
  try {
123
157
  var u=new URL(typeof input==='string'?input:input.url,location.href);
@@ -128,19 +162,21 @@ window.fetch=function(input,init){
128
162
  init.headers=h;
129
163
  }
130
164
  }catch(e){}
131
- return nativeFetch(input,init);
165
+ return nativeFetch(input,init).then(function(response){
166
+ recoverStaleServeAuth(response);
167
+ return response;
168
+ });
132
169
  };
133
170
  })();</script>`;
134
171
  }
135
172
  contentOrigins(req) {
136
173
  const host = hostWithoutPort(req.headers.host || 'localhost');
137
174
  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') {
175
+ // Released clients that predate protocol 2 reject the separate registrable
176
+ // content domain at the native WebView layer. Missing and unknown protocol
177
+ // values therefore stay on the compatibility origin forever; only an
178
+ // explicit client capability (or the staging override) opts into isolation.
179
+ if (cloud && !this.requestsIsolatedContentOrigins(req)) {
144
180
  const origin = requestOrigin(req);
145
181
  return { editOrigin: origin, playOrigin: origin };
146
182
  }
@@ -168,7 +204,10 @@ window.fetch=function(input,init){
168
204
  return { editOrigin: originFor('edit'), playOrigin: originFor('play') };
169
205
  }
170
206
  localContentOrigin(role) {
171
- return `http://127.0.0.1:${this.localContentPorts[role]}`;
207
+ const port = this.localContentPorts?.[role];
208
+ if (!port)
209
+ throw new Error('local content ports are not configured');
210
+ return `http://127.0.0.1:${port}`;
172
211
  }
173
212
  localContentProxyHeaders(role) {
174
213
  return {
@@ -231,8 +270,7 @@ window.fetch=function(input,init){
231
270
  if (typeof referer === 'string') {
232
271
  try {
233
272
  const referrerUrl = new URL(referer);
234
- if (referrerUrl.origin === requestOrigin(req) &&
235
- referrerUrl.pathname === '/index.html') {
273
+ if (referrerUrl.origin === requestOrigin(req) && referrerUrl.pathname === '/index.html') {
236
274
  return referrerUrl.searchParams.get('edit') === '0' ? 'play' : 'edit';
237
275
  }
238
276
  }
@@ -254,6 +292,17 @@ window.fetch=function(input,init){
254
292
  serveNonce: this.serveNonce,
255
293
  }, this.signingKey);
256
294
  }
295
+ requestsIsolatedContentOrigins(req) {
296
+ if (process.env.CASTLE_ISOLATED_CONTENT_ORIGINS === '1')
297
+ return true;
298
+ try {
299
+ return (new URL(req.url || '/', requestOrigin(req)).searchParams.get('mobileHostProtocol') ===
300
+ MOBILE_HOST_PROTOCOL);
301
+ }
302
+ catch {
303
+ return false;
304
+ }
305
+ }
257
306
  contentMac(role, publicPort, sandboxId, expiresAtSeconds, serveNonce) {
258
307
  return mintContentGrantLabel({ role, publicPort, sandboxId, expiresAtSeconds, serveNonce }, this.signingKey)
259
308
  .split('-')
@@ -0,0 +1,8 @@
1
+ import { type ResolvedServerConfig } from './castleJson.js';
2
+ export interface ServerBundle {
3
+ code: string;
4
+ sha256: string;
5
+ sizeBytes: number;
6
+ }
7
+ export declare function buildServerBundle(projectDir: string): Promise<ServerBundle | null>;
8
+ export declare function bundleServerModule(projectDir: string, config: ResolvedServerConfig, minify: boolean): Promise<string>;
@@ -0,0 +1,82 @@
1
+ import { createHash } from 'crypto';
2
+ import { createRequire } from 'module';
3
+ import * as path from 'path';
4
+ import { build } from 'vite';
5
+ import { resolveServerConfig, } from './castleJson.js';
6
+ import { forksOverlayPlugin, importsAliasPlugin } from './vitePlugins.js';
7
+ const WARN_BYTES = 1024 * 1024;
8
+ const MAX_BYTES = 5 * 1024 * 1024;
9
+ const VIRTUAL_ENTRY = '\0castle-server-entry';
10
+ // Build the artifact Cauldron executes. A deck without a valid server entry is
11
+ // not an error: multiplayer is opt-in, so callers can handle that as a skip (or
12
+ // clear a bundle they know they published earlier).
13
+ export async function buildServerBundle(projectDir) {
14
+ const config = resolveServerConfig(projectDir);
15
+ if (!config)
16
+ return null;
17
+ const code = await bundleServerModule(projectDir, config, true);
18
+ const sizeBytes = Buffer.byteLength(code, 'utf8');
19
+ if (sizeBytes > MAX_BYTES) {
20
+ throw new Error(`Server bundle is ${(sizeBytes / 1024 / 1024).toFixed(2)}MB; the maximum is 5MB.`);
21
+ }
22
+ if (sizeBytes > WARN_BYTES) {
23
+ console.warn(`Warning: Server bundle is ${(sizeBytes / 1024 / 1024).toFixed(2)}MB. ` +
24
+ 'Large server bundles take longer to start.');
25
+ }
26
+ return {
27
+ code,
28
+ sha256: createHash('sha256').update(code).digest('hex'),
29
+ sizeBytes,
30
+ };
31
+ }
32
+ // Dev and publish deliberately share the synthesized entry and Vite semantics.
33
+ // Dev keeps readable code; the published artifact is minified and checked below
34
+ // for the single-output-file contract.
35
+ export async function bundleServerModule(projectDir, config, minify) {
36
+ const sdkEntry = createRequire(path.join(projectDir, 'package.json')).resolve('castle-web-sdk/server');
37
+ const authorEntry = path.resolve(projectDir, config.entry);
38
+ const entryPlugin = {
39
+ name: 'castle-server-entry',
40
+ resolveId(id) {
41
+ return id === VIRTUAL_ENTRY ? VIRTUAL_ENTRY : null;
42
+ },
43
+ load(id) {
44
+ if (id !== VIRTUAL_ENTRY)
45
+ return null;
46
+ return (`import callbacks from ${JSON.stringify(authorEntry)};\n` +
47
+ `import { createCastleSessionBoot } from ${JSON.stringify(sdkEntry)};\n` +
48
+ 'export const __castleBootSession = createCastleSessionBoot(callbacks);\n');
49
+ },
50
+ };
51
+ const result = await build({
52
+ root: projectDir,
53
+ configFile: false,
54
+ logLevel: 'silent',
55
+ plugins: [forksOverlayPlugin(), importsAliasPlugin(), entryPlugin],
56
+ ssr: { noExternal: true },
57
+ build: {
58
+ write: false,
59
+ ssr: true,
60
+ target: 'node20',
61
+ minify,
62
+ sourcemap: false,
63
+ copyPublicDir: false,
64
+ assetsInlineLimit: Number.MAX_SAFE_INTEGER,
65
+ rollupOptions: {
66
+ input: VIRTUAL_ENTRY,
67
+ output: { format: 'es', inlineDynamicImports: true },
68
+ },
69
+ },
70
+ });
71
+ const output = Array.isArray(result) ? result[0] : result;
72
+ if (!('output' in output))
73
+ throw new Error('unexpected server build result');
74
+ const chunk = output.output.find((item) => item.type === 'chunk' && item.isEntry);
75
+ if (!chunk || chunk.type !== 'chunk')
76
+ throw new Error('server bundle produced no entry chunk');
77
+ if (output.output.length !== 1) {
78
+ const extras = output.output.filter((item) => item !== chunk).map((item) => item.fileName);
79
+ throw new Error(`server bundle produced additional files: ${extras.join(', ')}`);
80
+ }
81
+ return chunk.code;
82
+ }