castle-web-cli 0.4.244 → 0.4.246

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/serve.js CHANGED
@@ -33,7 +33,7 @@ import { devSocialFixtureKey, devSocialGraphql, devSocialUser, } from './devSoci
33
33
  import { DevExperiments } from './devExperiments.js';
34
34
  import { devSaveGraphql } from './devSessionStorage.js';
35
35
  import { serveOracleStream } from './deckAgentRoute.js';
36
- import { ServeSecurity } from './serveSecurity.js';
36
+ import { ServeSecurity, } from './serveSecurity.js';
37
37
  import { atomicWriteFileSync } from './atomicFile.js';
38
38
  import { isSameOriginUpgrade } from './wsOrigin.js';
39
39
  import { createAssetCompression } from './assetCompression.js';
@@ -506,6 +506,47 @@ function hostnameFromHeader(value) {
506
506
  }
507
507
  return value.split(':')[0].toLowerCase();
508
508
  }
509
+ /**
510
+ * True for an address only this machine can reach. Takes the address a server
511
+ * actually bound (`server.address().address`) or a `--host` value; no host means
512
+ * Vite's default, `localhost`.
513
+ */
514
+ export function isLoopbackBindHost(host) {
515
+ if (host === undefined)
516
+ return true;
517
+ const bare = host.replace(/^\[|\]$/g, '').toLowerCase();
518
+ return (bare === 'localhost' ||
519
+ bare === '::1' ||
520
+ /^(?:::ffff:)?127(?:\.\d{1,3}){3}$/.test(bare));
521
+ }
522
+ /**
523
+ * The warning a serve prints when its listener is reachable beyond loopback.
524
+ * `boundAddress` is the address the listener really holds, so a deck's own
525
+ * Vite `server.host` and a hostname `--host` are classified by what they bound.
526
+ * The editor shell hands its browser client the IDE's credentials, terminal
527
+ * included: whoever reaches the port can change the project and run commands.
528
+ * Null on loopback. In a Castle cloud sandbox (CASTLE_SANDBOX_ID) the listener
529
+ * binds every interface of its container on purpose; it says so in one line
530
+ * rather than staying silent, since the variable alone proves nothing.
531
+ */
532
+ export function networkExposureWarning(boundAddress, env = process.env) {
533
+ if (isLoopbackBindHost(boundAddress))
534
+ return null;
535
+ const bare = (boundAddress ?? '').replace(/^\[|\]$/g, '');
536
+ const wildcard = bare === '0.0.0.0' || bare === '::' || bare === '';
537
+ const where = wildcard ? 'every network interface' : bare;
538
+ if (env.CASTLE_SANDBOX_ID) {
539
+ return `Serving on ${where} (CASTLE_SANDBOX_ID is set: expected inside a Castle cloud sandbox, behind its authenticated proxy; anywhere else this exposes the editor to the network).`;
540
+ }
541
+ return [
542
+ `WARNING: serving on ${where}, not just this machine.`,
543
+ ' This serve has no login of its own. Anyone who can reach this address can open',
544
+ ' the editor, read and change the project files, and run commands in its terminal',
545
+ ' as the user running this CLI.',
546
+ ' Use it only on a network you trust; omit --host/--lan (and any server.host in',
547
+ ' the deck\'s Vite config) to stay on localhost.',
548
+ ].join('\n');
549
+ }
509
550
  export function isAllowedShellHost(hostHeader, configuredHost) {
510
551
  const host = hostnameFromHeader(hostHeader);
511
552
  if (!host)
@@ -643,12 +684,21 @@ export function castlePlugin(security, ideServer, agentServer, scriptErrors, pro
643
684
  const reqPath = (req.url || '/').split('?')[0];
644
685
  const trustedSurface = req.headers['x-castle-sandbox-surface'];
645
686
  const verifiedRole = security.verifyContentRequest(req);
646
- const contentRole = verifiedRole ?? security.compatibilityContentRole(req);
687
+ const compat = verifiedRole ? null : security.compatibilityContent(req);
688
+ const contentRole = verifiedRole ?? compat?.role ?? null;
647
689
  const content = trustedSurface === 'content' || contentRole !== null;
648
690
  if (content && !contentRole) {
649
691
  res.writeHead(403).end('invalid content capability');
650
692
  return;
651
693
  }
694
+ if (compat?.sandboxed) {
695
+ // A referrer-less static load on the shell origin (compatibility
696
+ // mode, a `no-referrer` deck). Rendered as a document it gets an
697
+ // opaque origin; loaded as a subresource the CSP does not apply.
698
+ res.setHeader('Content-Security-Policy', 'sandbox');
699
+ res.setHeader('X-Content-Type-Options', 'nosniff');
700
+ sandboxedStaticRequests.set(req, reqPath);
701
+ }
652
702
  if (!content && !isAllowedShellHost(req.headers.host, configuredHost)) {
653
703
  res.writeHead(403).end('untrusted host');
654
704
  return;
@@ -767,6 +817,20 @@ export function castlePlugin(security, ideServer, agentServer, scriptErrors, pro
767
817
  return;
768
818
  }
769
819
  devExperimentsFor(projectDir).noteUrl(req.url);
820
+ // An open shell renewing its content grants before they run out
821
+ // (contentFrames.ts). Same origins the shell route would give it now.
822
+ if (reqPath === CONTENT_ORIGINS_PATH) {
823
+ if (req.method !== 'GET') {
824
+ res.writeHead(405).end();
825
+ return;
826
+ }
827
+ res.writeHead(200, {
828
+ 'content-type': 'application/json',
829
+ 'cache-control': 'no-store',
830
+ });
831
+ res.end(JSON.stringify(security.refreshedContentOrigins(req)));
832
+ return;
833
+ }
770
834
  // The split-view shell (`/`) + its static assets are served outside
771
835
  // Vite's module pipeline; the deck itself loads in the iframe via
772
836
  // `/index.html`, which Vite still serves normally.
@@ -780,9 +844,32 @@ export function castlePlugin(security, ideServer, agentServer, scriptErrors, pro
780
844
  // deck HTML/modules, which would put untrusted code beside the serve token.
781
845
  res.writeHead(404).end();
782
846
  });
847
+ // After Vite's HTML fallback, before it serves HTML: a sandboxed static
848
+ // load (see compatibilityContent) never gets a page -- neither the SPA
849
+ // fallback's index.html nor an `.html` rewrite or file.
850
+ return () => {
851
+ server.middlewares.use((req, res, next) => {
852
+ const original = sandboxedStaticRequests.get(req);
853
+ if (original === undefined) {
854
+ next();
855
+ return;
856
+ }
857
+ const current = (req.url || '/').split('?')[0];
858
+ if (current !== original || /\.html?$/i.test(current)) {
859
+ res.removeHeader('Content-Security-Policy');
860
+ res.writeHead(404).end();
861
+ return;
862
+ }
863
+ next();
864
+ });
865
+ };
783
866
  },
784
867
  };
785
868
  }
869
+ // The shell endpoint an open shell renews its content origins from.
870
+ export const CONTENT_ORIGINS_PATH = '/__castle/content-origins';
871
+ // Requests admitted as sandboxed static loads, with the path they asked for.
872
+ const sandboxedStaticRequests = new WeakMap();
786
873
  // The serve's own user, fetched once and cached for the serve lifetime so
787
874
  // User.getCurrent works in dev. Config may carry only a token: a sandbox
788
875
  // starts the serve with CASTLE_TOKEN alone and no config.json, so the userId
@@ -1215,6 +1302,7 @@ export async function serve(dir, options = {}) {
1215
1302
  const castleDir = path.join(projectDir, '.castle');
1216
1303
  if (!fs.existsSync(castleDir))
1217
1304
  fs.mkdirSync(castleDir, { recursive: true });
1305
+ security.useProjectState(projectDir);
1218
1306
  // The platform guide, fresh from this CLI, and the root CLAUDE.md's @import
1219
1307
  // of it (platformDoc.ts). After autoUpdateImports, so the guide's media list
1220
1308
  // sees the imports this serve will run with.
@@ -1445,6 +1533,13 @@ export async function serve(dir, options = {}) {
1445
1533
  // Bring content up first so `--open` cannot race an iframe against a port
1446
1534
  // that is not listening yet. Vite opens the shell from inside `vite.listen()`.
1447
1535
  await vite.listen();
1536
+ // Classify exposure by what the listener really bound: a deck's Vite config
1537
+ // can set server.host even when no --host was passed.
1538
+ const bound = vite.httpServer?.address();
1539
+ const boundAddress = bound && typeof bound === 'object' ? bound.address : options.host;
1540
+ const exposure = networkExposureWarning(boundAddress);
1541
+ if (exposure)
1542
+ console.warn(exposure);
1448
1543
  // Atomic so a replacement lands under a new inode: the owned-removal check
1449
1544
  // in removeServeJsonIfOwned compares inodes to tell a rewrite apart.
1450
1545
  atomicWriteFileSync(serveJsonPath, JSON.stringify({
@@ -1454,6 +1549,8 @@ export async function serve(dir, options = {}) {
1454
1549
  wsPort: port,
1455
1550
  wsPath: '/__castle/ws',
1456
1551
  pid: process.pid,
1552
+ // What the listener really bound, so a detached parent can warn too.
1553
+ boundAddress,
1457
1554
  contentPlayUrl: security.localContentOrigin('play'),
1458
1555
  }) + '\n');
1459
1556
  // After listen and serve.json: a failed startup must not spend a task's
@@ -1584,6 +1681,10 @@ async function serveDetached(projectDir, options) {
1584
1681
  await new Promise((r) => setTimeout(r, 200));
1585
1682
  continue;
1586
1683
  }
1684
+ // The child's warning went to its log; repeat it where the caller sees it.
1685
+ const detachedExposure = networkExposureWarning(typeof info.boundAddress === 'string' ? info.boundAddress : options.host);
1686
+ if (detachedExposure)
1687
+ console.warn(detachedExposure);
1587
1688
  console.log(`Started serve in background: http://localhost:${info.port}`);
1588
1689
  console.log(`PID: ${childPid}`);
1589
1690
  console.log(`Logs: ${logPath}`);
@@ -5,6 +5,28 @@ export type LocalContentPorts = Record<ContentRole, number>;
5
5
  export declare const SERVE_AUTH_FAILURE_HEADER = "x-castle-serve-auth";
6
6
  export declare const SERVE_AUTH_FAILURE_VALUE = "invalid";
7
7
  export declare const MOBILE_HOST_PROTOCOL = "2";
8
+ export declare const COMPAT_CONTENT_PARAM = "castleCompat";
9
+ export declare const PROTOCOL2_MARKER_FILE = "protocol2-shell-seen.json";
10
+ export declare const CONTENT_ORIGIN_FILE = "content-origin.json";
11
+ /** What `compatibilityContent` grants: a role, and whether the response must be sandboxed. */
12
+ export interface CompatibilityContent {
13
+ role: ContentRole;
14
+ /**
15
+ * A referrer-less static load: the response must carry
16
+ * `Content-Security-Policy: sandbox` and `X-Content-Type-Options: nosniff`,
17
+ * and must never be Vite's HTML fallback.
18
+ */
19
+ sandboxed: boolean;
20
+ }
21
+ /**
22
+ * A native app WebView, which is all a released Castle app opens the editor in:
23
+ * iOS/iPadOS WKWebView's default user agent has AppleWebKit but no `Safari/`
24
+ * token (every Safari, and every Chromium browser, carries one), and Android
25
+ * System WebView marks itself `; wv)`. Page script cannot change the user agent
26
+ * its browser sends, so deck code in a desktop or mobile browser can never
27
+ * look like this. Exported for the tests.
28
+ */
29
+ export declare function isNativeWebViewUserAgent(userAgent: string | undefined): boolean;
8
30
  export declare function mintContentGrantLabel(grant: {
9
31
  role: ContentRole;
10
32
  publicPort: number;
@@ -17,13 +39,52 @@ export declare class ServeSecurity {
17
39
  readonly serveToken: string;
18
40
  private readonly contentProxyToken;
19
41
  private readonly signingKey;
20
- private readonly serveNonce;
42
+ private serveNonce;
43
+ private readonly retiredNonces;
44
+ private projectDir;
45
+ private projectRealpath;
46
+ private projectId;
21
47
  private contentGrantExpiresAtSeconds;
22
48
  private readonly pathKey;
49
+ private readonly compatContentKey;
50
+ private protocol2ShellSeen;
23
51
  private readonly tickets;
24
52
  private localContentPorts;
25
53
  private localContentHost;
26
54
  constructor(publicPort: number, localContentPorts?: LocalContentPorts);
55
+ /**
56
+ * Keep this serve's state in `projectDir` (`.castle/runtime/`, see
57
+ * projectState.ts): the protocol-2 marker and the content-origin record.
58
+ *
59
+ * Content origins stay stable across serves of this project: the record
60
+ * holds a random project id and the current grant expiry, and the nonce in
61
+ * every label is derived from the signing key, that id and the project's
62
+ * real path. The nonce is in the grant MAC input (whose format Ghost also
63
+ * verifies, so it cannot grow a field), so a record copied into another
64
+ * project -- or another project later served on the same port -- yields a
65
+ * different nonce and never verifies this project's labels. A missing or
66
+ * malformed record is absent (the first mint writes a fresh one); deck code
67
+ * that rewrites it only moves its own project's origins.
68
+ *
69
+ * Files an earlier build kept directly in `.castle/` (which cloud checkpoint
70
+ * capture rejects) are migrated: the marker moves, a v1 record is dropped.
71
+ */
72
+ useProjectState(projectDir: string): void;
73
+ private adoptProjectId;
74
+ /** The state file `name`, if its directory is safe (created on demand), else null. */
75
+ private stateFile;
76
+ private migrateLegacyState;
77
+ /**
78
+ * Whether a protocol-2 app shell has opened this project, read from disk on
79
+ * every call: another serve of the same project may have written it since
80
+ * this one started. Anything at the marker path counts, and so does an
81
+ * unsafe state directory (fail closed).
82
+ */
83
+ private protocol2MarkerPresent;
84
+ private writeProtocol2Marker;
85
+ private readContentOriginRecord;
86
+ private writeContentOriginRecord;
87
+ private noteProtocol2Shell;
27
88
  setLocalContentPorts(ports: LocalContentPorts): void;
28
89
  setLocalContentHost(host: string): void;
29
90
  authorizeHttp(req: http.IncomingMessage): boolean;
@@ -47,9 +108,26 @@ export declare class ServeSecurity {
47
108
  consumeLegacyContentTicket(req: http.IncomingMessage): ContentRole | null;
48
109
  private pruneTickets;
49
110
  shellBootstrap(req: http.IncomingMessage): string;
50
- contentOrigins(req: http.IncomingMessage): {
111
+ contentOrigins(req: http.IncomingMessage, options?: {
112
+ allowCompatibility?: boolean;
113
+ }): {
51
114
  editOrigin: string;
52
115
  playOrigin: string;
116
+ contentParams?: Record<string, string>;
117
+ /** Set only for signed (cloud, isolated) origins: when their labels expire. */
118
+ expiresAtSeconds?: number;
119
+ };
120
+ /**
121
+ * What `GET /__castle/content-origins` returns to an open shell refreshing
122
+ * its grants. Never compatibility origins: the refresh request carries none
123
+ * of what admission needs (no `embed=mobile`, a sandbox referrer), and a
124
+ * compatibility shell has no expiry to refresh. Isolated origins are exactly
125
+ * what the shell route would give the same shell now.
126
+ */
127
+ refreshedContentOrigins(req: http.IncomingMessage): {
128
+ edit: string;
129
+ play: string;
130
+ expiresAtSeconds: number | null;
53
131
  };
54
132
  private contentGrantExpiry;
55
133
  /**
@@ -68,8 +146,32 @@ export declare class ServeSecurity {
68
146
  localContentProxyHeaders(role: ContentRole): Record<string, string>;
69
147
  verifyContentRequest(req: http.IncomingMessage): ContentRole | null;
70
148
  compatibilityContentRole(req: http.IncomingMessage): ContentRole | null;
149
+ /**
150
+ * The content role a compatibility-mode request gets on the shell origin,
151
+ * and whether its response must be sandboxed (see CompatibilityContent).
152
+ */
153
+ compatibilityContent(req: http.IncomingMessage): CompatibilityContent | null;
71
154
  shellOrigin(req: http.IncomingMessage): string;
72
155
  private mintContentLabel;
73
- private requestsIsolatedContentOrigins;
156
+ /**
157
+ * Whether this shell request gets compatibility origins (edit and play on the
158
+ * shell origin, the shell's own authority). Only a released mobile app may:
159
+ * castle-www forwards `embed=mobile` (every released app sends it) and, from
160
+ * protocol-2 apps, `mobileHostProtocol=2`. Those parameters are attacker
161
+ * controlled -- an isolated deck can navigate its frame or a new window to
162
+ * `?embed=mobile` -- so admission also needs what deck code cannot forge:
163
+ *
164
+ * - a native WebView user agent (a script cannot change its browser's UA,
165
+ * so no desktop or mobile browser is ever admitted);
166
+ * - castle-www as the embedder: a castle.xyz referrer and, where the browser
167
+ * sends Fetch Metadata, not a cross-site request (a navigation from the
168
+ * castlexyz.com content domain is cross-site and carries its referrer);
169
+ * - no protocol-2 shell ever seen on this project (see protocol2ShellSeen): inside
170
+ * a protocol-2 app, deck code can top-navigate to castle.xyz/admin/cloud
171
+ * with embed=mobile alone, and the request would otherwise look legitimate.
172
+ *
173
+ * See docs/mobile-webview-host-protocol.md for what remains.
174
+ */
175
+ private admitCompatibilityShell;
74
176
  private contentMac;
75
177
  }