castle-web-cli 0.4.149 → 0.4.151

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 (49) hide show
  1. package/dist/agent.d.ts +1 -0
  2. package/dist/agent.js +12 -4
  3. package/dist/api.d.ts +45 -1
  4. package/dist/api.js +34 -2
  5. package/dist/castle-host/host.d.ts +17 -0
  6. package/dist/castle-host/host.js +10 -7
  7. package/dist/castleJson.d.ts +15 -0
  8. package/dist/castleJson.js +36 -0
  9. package/dist/devSessionChild.d.ts +1 -0
  10. package/dist/devSessionChild.js +129 -0
  11. package/dist/devSessionServer.d.ts +19 -0
  12. package/dist/devSessionServer.js +511 -0
  13. package/dist/headlessCover.js +28 -0
  14. package/dist/index.js +8 -8
  15. package/dist/init.js +9 -1
  16. package/dist/list-decks.js +7 -6
  17. package/dist/native/playtest-remote.d.ts +3 -0
  18. package/dist/native/playtest-remote.js +113 -0
  19. package/dist/preview.d.ts +1 -1
  20. package/dist/preview.js +4 -2
  21. package/dist/save-deck.js +82 -16
  22. package/dist/serve.js +245 -88
  23. package/dist/serveSecurity.d.ts +7 -1
  24. package/dist/serveSecurity.js +61 -10
  25. package/dist/serverBundle.d.ts +8 -0
  26. package/dist/serverBundle.js +82 -0
  27. package/dist/shell/assets/{index-BzFzFtEP.js → index-Dlhc3eZW.js} +42 -42
  28. package/dist/shell/assets/index-DwezawBs.css +1 -0
  29. package/dist/shell/index.html +2 -2
  30. package/kits/blank/.castle/agent/children.json +1 -0
  31. package/kits/blank/.castle/agent/messages.json +9 -0
  32. package/kits/blank/.castle/agent/pending-sends.json +1 -0
  33. package/kits/blank/.castle/agent/tasks/index.md +2 -0
  34. package/kits/blank/.castle/docs/platform.md +36 -0
  35. package/kits/blank/castle.json +5 -2
  36. package/kits/blank/node_modules/.vite/deps/_metadata.json +8 -0
  37. package/kits/blank/node_modules/.vite/deps/package.json +3 -0
  38. package/kits/physics-2d/behaviors/Collider.jsx +1 -2
  39. package/kits/physics-2d/behaviors/Joints.jsx +1 -1
  40. package/kits/physics-2d/castle.json +1 -1
  41. package/kits/physics-2d/editors/BlueprintLibrary.jsx +33 -3
  42. package/kits/physics-2d/editors/SceneEditor.jsx +171 -57
  43. package/kits/physics-2d/editors/SingleEditor.jsx +6 -0
  44. package/kits/physics-2d/engine/blueprint.js +106 -14
  45. package/kits/physics-2d/engine/scene.js +9 -2
  46. package/kits/physics-2d/engine/ui.jsx +30 -2
  47. package/kits/physics-2d/engine/ui.module.css +59 -0
  48. package/package.json +1 -1
  49. 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
+ const BROWSER_GRANT_SECONDS = 3 * 60;
6
9
  export const MOBILE_HOST_PROTOCOL = '2';
7
10
  function base32Lower(bytes) {
8
11
  let bits = 0;
@@ -50,23 +53,35 @@ export function mintContentGrantLabel(grant, signingKey) {
50
53
  }
51
54
  export class ServeSecurity {
52
55
  publicPort;
53
- localContentPorts;
54
56
  serveToken = randomBytes(32).toString('base64url');
55
57
  contentProxyToken = randomBytes(32).toString('base64url');
56
58
  signingKey = process.env.CASTLE_AGENT_TOKEN || randomBytes(32).toString('base64url');
57
59
  serveNonce = base32Lower(randomBytes(8));
58
60
  tickets = new Map();
59
- constructor(publicPort, localContentPorts = {
60
- edit: publicPort + 2,
61
- play: publicPort + 3,
62
- }) {
61
+ localContentPorts;
62
+ constructor(publicPort, localContentPorts) {
63
63
  this.publicPort = publicPort;
64
- this.localContentPorts = localContentPorts;
64
+ this.localContentPorts = localContentPorts ?? null;
65
+ }
66
+ setLocalContentPorts(ports) {
67
+ if (this.localContentPorts)
68
+ throw new Error('local content ports are already configured');
69
+ if (ports.edit === ports.play)
70
+ throw new Error('edit and play content ports must be distinct');
71
+ this.localContentPorts = ports;
65
72
  }
66
73
  authorizeHttp(req) {
67
74
  const value = req.headers['x-castle-serve-token'];
68
75
  return typeof value === 'string' && safeEqual(value, this.serveToken);
69
76
  }
77
+ rejectHttpAuth(res) {
78
+ res
79
+ .writeHead(403, {
80
+ [SERVE_AUTH_FAILURE_HEADER]: SERVE_AUTH_FAILURE_VALUE,
81
+ 'cache-control': 'no-store',
82
+ })
83
+ .end();
84
+ }
70
85
  issueTicket(endpoint) {
71
86
  this.pruneTickets();
72
87
  const ticket = randomBytes(16).toString('base64url');
@@ -119,6 +134,25 @@ window.__CASTLE_SERVE_TOKEN__=${JSON.stringify(this.serveToken)};
119
134
  window.__CASTLE_CONTENT_ORIGINS__=${JSON.stringify({ edit: editOrigin, play: playOrigin })};
120
135
  window.__CASTLE_HOST_ORIGIN__=${JSON.stringify(hostOrigin)};
121
136
  var nativeFetch=window.fetch.bind(window);
137
+ var authReloadKey='castle:serve-auth-reload';
138
+ var authReloadScheduled=false;
139
+ var authReloadStorage=true;
140
+ try {
141
+ var previousAuthReload=sessionStorage.getItem(authReloadKey);
142
+ if(previousAuthReload&&previousAuthReload!==window.__CASTLE_SERVE_TOKEN__){
143
+ sessionStorage.removeItem(authReloadKey);
144
+ }
145
+ }catch(e){authReloadStorage=false;}
146
+ function recoverStaleServeAuth(response){
147
+ if(response.headers.get(${JSON.stringify(SERVE_AUTH_FAILURE_HEADER)})!==${JSON.stringify(SERVE_AUTH_FAILURE_VALUE)})return;
148
+ if(authReloadScheduled||!authReloadStorage)return;
149
+ try {
150
+ if(sessionStorage.getItem(authReloadKey)===window.__CASTLE_SERVE_TOKEN__)return;
151
+ sessionStorage.setItem(authReloadKey,window.__CASTLE_SERVE_TOKEN__);
152
+ }catch(e){authReloadStorage=false;return;}
153
+ authReloadScheduled=true;
154
+ window.location.reload();
155
+ }
122
156
  window.fetch=function(input,init){
123
157
  try {
124
158
  var u=new URL(typeof input==='string'?input:input.url,location.href);
@@ -129,7 +163,10 @@ window.fetch=function(input,init){
129
163
  init.headers=h;
130
164
  }
131
165
  }catch(e){}
132
- return nativeFetch(input,init);
166
+ return nativeFetch(input,init).then(function(response){
167
+ recoverStaleServeAuth(response);
168
+ return response;
169
+ });
133
170
  };
134
171
  })();</script>`;
135
172
  }
@@ -168,7 +205,22 @@ window.fetch=function(input,init){
168
205
  return { editOrigin: originFor('edit'), playOrigin: originFor('play') };
169
206
  }
170
207
  localContentOrigin(role) {
171
- return `http://127.0.0.1:${this.localContentPorts[role]}`;
208
+ const port = this.localContentPorts?.[role];
209
+ if (!port)
210
+ throw new Error('local content ports are not configured');
211
+ return `http://127.0.0.1:${port}`;
212
+ }
213
+ /** A short-lived play URL for one shared-browser admission attempt. */
214
+ browserContentOrigin(role = 'play') {
215
+ const sandboxId = process.env.CASTLE_SANDBOX_ID;
216
+ if (!sandboxId || !/^[a-z0-9]{14}$/.test(sandboxId))
217
+ return null;
218
+ const env = process.env.CASTLE_SANDBOX_ENV === 'staging' ? 'staging' : 'prod';
219
+ const domain = env === 'staging'
220
+ ? 'sandboxes-staging.castlexyz.com'
221
+ : 'sandboxes.castlexyz.com';
222
+ const expiresAtSeconds = Math.floor(Date.now() / 1000) + BROWSER_GRANT_SECONDS;
223
+ return `https://${this.mintContentLabel(role, sandboxId, expiresAtSeconds)}.${domain}`;
172
224
  }
173
225
  localContentProxyHeaders(role) {
174
226
  return {
@@ -231,8 +283,7 @@ window.fetch=function(input,init){
231
283
  if (typeof referer === 'string') {
232
284
  try {
233
285
  const referrerUrl = new URL(referer);
234
- if (referrerUrl.origin === requestOrigin(req) &&
235
- referrerUrl.pathname === '/index.html') {
286
+ if (referrerUrl.origin === requestOrigin(req) && referrerUrl.pathname === '/index.html') {
236
287
  return referrerUrl.searchParams.get('edit') === '0' ? 'play' : 'edit';
237
288
  }
238
289
  }
@@ -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
+ }