castle-web-cli 0.4.244 → 0.4.245

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/api.d.ts CHANGED
@@ -267,6 +267,7 @@ export interface DeckMeta {
267
267
  }
268
268
  export declare function deckMeta(deckId: string): Promise<DeckMeta | null>;
269
269
  export declare function webDeckSource(deckId: string): Promise<WebDeckSource | null>;
270
+ export declare function webDeckSourceAtVersion(deckId: string, version: string): Promise<WebDeckSource | null>;
270
271
  export interface SavedSourceVersion {
271
272
  s3Key: string;
272
273
  archiveUrl: string;
package/dist/api.js CHANGED
@@ -450,6 +450,19 @@ export async function webDeckSource(deckId) {
450
450
  handleAPIError(data);
451
451
  return pickData(data, 'webDeckSource');
452
452
  }
453
+ // The deck's source as it was saved at `version` (a webDeckSource updatedAt, as an import
454
+ // pin records it). Ghost serves older versions of the castle account's kits to anyone who
455
+ // may read the kit, and of any deck to its publisher; null when it does not serve that
456
+ // version. A Ghost without the field fails this, and callers fall back to webDeckSource.
457
+ export async function webDeckSourceAtVersion(deckId, version) {
458
+ const data = await graphql(`query($deckId: ID!, $version: String!) {
459
+ webDeckSourceVersion(deckId: $deckId, version: $version) {
460
+ deckId archiveUrl s3Key updatedAt
461
+ }
462
+ }`, { deckId, version });
463
+ handleAPIError(data);
464
+ return pickData(data, 'webDeckSourceVersion');
465
+ }
453
466
  // Every saved version of the deck's source, newest first (Ghost lists at most 50), for its
454
467
  // creator or an edit collaborator. A Ghost without the field fails this, as does anyone else.
455
468
  export async function savedSourceHistory(deckId, timeoutMs) {
@@ -0,0 +1,13 @@
1
+ /** The shell renews its content origins when less than this remains on them. */
2
+ export declare const CONTENT_ORIGIN_REFRESH_BEFORE_SECONDS: number;
3
+ /**
4
+ * Margin between the two: the serve reuses a grant (same hostname, same
5
+ * browser storage and module cache) only while at least
6
+ * REFRESH_BEFORE + this remains, so every grant it hands out -- to a new
7
+ * shell, a reopened one, or a renewal -- starts outside the shell's renewal
8
+ * window by at least this much. It also absorbs a shell clock running up to
9
+ * this far ahead of the serve's.
10
+ */
11
+ export declare const CONTENT_ORIGIN_REUSE_MARGIN_SECONDS: number;
12
+ /** The least a grant handed to a shell has left: about 10h45m of reuse per 12h grant. */
13
+ export declare const MIN_CONTENT_GRANT_REMAINING_SECONDS: number;
@@ -0,0 +1,15 @@
1
+ // Timing shared by the serve (which mints signed content-origin grants) and the
2
+ // shell (which renews them), so the two can never drift into a renewal loop.
3
+ /** The shell renews its content origins when less than this remains on them. */
4
+ export const CONTENT_ORIGIN_REFRESH_BEFORE_SECONDS = 60 * 60;
5
+ /**
6
+ * Margin between the two: the serve reuses a grant (same hostname, same
7
+ * browser storage and module cache) only while at least
8
+ * REFRESH_BEFORE + this remains, so every grant it hands out -- to a new
9
+ * shell, a reopened one, or a renewal -- starts outside the shell's renewal
10
+ * window by at least this much. It also absorbs a shell clock running up to
11
+ * this far ahead of the serve's.
12
+ */
13
+ export const CONTENT_ORIGIN_REUSE_MARGIN_SECONDS = 15 * 60;
14
+ /** The least a grant handed to a shell has left: about 10h45m of reuse per 12h grant. */
15
+ export const MIN_CONTENT_GRANT_REMAINING_SECONDS = CONTENT_ORIGIN_REFRESH_BEFORE_SECONDS + CONTENT_ORIGIN_REUSE_MARGIN_SECONDS;
package/dist/imports.js CHANGED
@@ -8,6 +8,7 @@ import { normalizeDeckPackageJson } from './normalize.js';
8
8
  import { getKitsDir } from './localPaths.js';
9
9
  import { shippedFrameworkKit, shippedKitAlias } from './kitCatalog.js';
10
10
  import { SDK_PACKAGE } from './sdkResolve.js';
11
+ import { classifySaveFailure } from './saveFailure.js';
11
12
  import { importIsOnTrustedAccount, TRUSTED_IMPORT_ACCOUNT } from './importTrust.js';
12
13
  import { writePlatformDocs } from './platformDoc.js';
13
14
  import { findImportUpdateHook, runImportUpdateHook, } from './importUpdateHook.js';
@@ -530,19 +531,40 @@ export async function restoreMissingImports(deckDir) {
530
531
  if (fs.existsSync(destDir))
531
532
  continue;
532
533
  if (pin?.deckId) {
533
- const source = await api.webDeckSource(pin.deckId).catch(() => null);
534
+ // The pinned save first: Ghost indexes each save of a deck and serves a kit's
535
+ // older ones by version. When Ghost answers that it will not -- null (another
536
+ // account's deck, a save from before the index), an error, a Ghost or sandbox
537
+ // proxy without the field -- the latest is placed instead, as before. When Ghost
538
+ // could not be reached, nothing is placed: a later install skips an import that
539
+ // is already there, so placing the latest now would keep it past the outage.
540
+ let pinned = null;
541
+ if (pin.version) {
542
+ try {
543
+ pinned = await api.webDeckSourceAtVersion(pin.deckId, pin.version);
544
+ }
545
+ catch (e) {
546
+ const { reason } = classifySaveFailure(null, e);
547
+ // A gateway error (the sandbox proxy's 502 when Ghost is down) reaches here as
548
+ // api.graphql's "Castle API <status>"; it is an outage, not an answer.
549
+ const gatewayFailed = e instanceof Error && /^Castle API 5\d\d\b/.test(e.message);
550
+ if (reason === 'network' || reason === 'upload_timeout' || gatewayFailed) {
551
+ console.warn(`Could not reach Castle to fetch import "${alias}" at ${pin.version}; skipped it. Run \`castle-web install\` again.`);
552
+ continue;
553
+ }
554
+ }
555
+ }
556
+ const source = pinned ?? (await api.webDeckSource(pin.deckId).catch(() => null));
534
557
  if (!source) {
535
558
  console.warn(`Could not fetch import "${alias}" (${pin.deckId}); it has no source on the server.`);
536
559
  continue;
537
560
  }
538
561
  await fetchDeckSourceInto(source.archiveUrl, destDir);
539
- // The server only serves its latest archive, so what landed here is
540
- // `source.updatedAt`, not necessarily what the pin says. Record the
541
- // truth: the pin stays as committed, and publish-kits compares the two
542
- // to refuse bundling against files no pin describes.
562
+ // A fallback places `source.updatedAt`, not necessarily what the pin says.
563
+ // Record the truth: the pin stays as committed, and publish-kits compares
564
+ // the two to refuse bundling against files no pin describes.
543
565
  writeImportVersion(destDir, { deckId: pin.deckId, version: source.updatedAt });
544
566
  if (source.updatedAt !== pin.version) {
545
- console.warn(`Import "${alias}" is pinned at ${pin.version}, but the server only has ${source.updatedAt}, so that is what was placed. ` +
567
+ console.warn(`Import "${alias}" is pinned at ${pin.version}, but the server does not serve that version, so ${source.updatedAt} was placed. ` +
546
568
  '`castle-web check` and `save-deck` refuse until the two agree (see `--pin-installed-imports`).');
547
569
  }
548
570
  }
package/dist/index.js CHANGED
@@ -187,7 +187,7 @@ function usageText() {
187
187
  return `Usage:
188
188
  castle-web init <dir> [--deck-id ID] [--card-id ID] [--kit NAME] [--port PORT] (kits: ${initKits}; default physics-2d)
189
189
  castle-web init <dir> --remix <deckId> [--deck-id ID] [--card-id ID] [--port PORT] (starts from a published deck instead of a kit)
190
- castle-web serve [dir] [--port PORT] [--host HOST] [--open] [--detach]
190
+ castle-web serve [dir] [--port PORT] [--host HOST | --lan] [--open] [--detach] (listens on localhost only by default; --host ADDR binds that address and --lan is --host 0.0.0.0 -- both expose the unauthenticated editor, its terminal and the project files to the network)
191
191
  castle-web restart [--port PORT]
192
192
  castle-web screenshot [--out FILE] [--port PORT]
193
193
  castle-web save-deck [dir] [--title TITLE] [--caption TEXT] [--visibility unlisted|private] [--force] [--pin-installed-imports] [--chunked-bundle] (--force: save over a newer saved copy; --pin-installed-imports: move import pins to the versions imports/ holds instead of refusing; --chunked-bundle: publish the JS as cacheable classic-script chunks, as castle.json "bundle": { "chunks": "classic" } does)
@@ -585,7 +585,25 @@ async function main() {
585
585
  case 'serve': {
586
586
  const dir = findPositionalDir();
587
587
  const port = getFlagValue('--port');
588
- const host = getFlagValue('--host');
588
+ // Only the spaced form is parsed; reject the rest rather than drop it
589
+ // silently (with --lan, a dropped --host=127.0.0.1 would expose the serve).
590
+ const unparsed = args.find((arg) => /^--(?:host|lan)=/.test(arg));
591
+ if (unparsed) {
592
+ console.error(`Unsupported flag spelling ${unparsed.split('=')[0]}=...; pass it as "${unparsed.split('=')[0]} VALUE".`);
593
+ process.exit(1);
594
+ }
595
+ let host = getFlagValue('--host');
596
+ if (hasFlag('--host') && (host === undefined || host.trim() === '' || host.startsWith('--'))) {
597
+ console.error('--host needs an address, for example --host 127.0.0.1 (or --lan for every interface).');
598
+ process.exit(1);
599
+ }
600
+ if (hasFlag('--lan')) {
601
+ if (host !== undefined && host !== '0.0.0.0') {
602
+ console.error('--lan means --host 0.0.0.0; pass one or the other.');
603
+ process.exit(1);
604
+ }
605
+ host = '0.0.0.0';
606
+ }
589
607
  const open = args.includes('--open');
590
608
  const detach = args.includes('--detach');
591
609
  await serve(dir, { port, host, open, detach });
package/dist/init.js CHANGED
@@ -64,7 +64,7 @@ const BARE_SCAFFOLDS = [
64
64
  // Registry version of castle-web-sdk to inject when scaffolding from a
65
65
  // globally-installed castle-web (not from inside the workspace). Bumped
66
66
  // alongside cli/sdk version bumps.
67
- const PUBLISHED_SDK_VERSION = '0.4.56';
67
+ const PUBLISHED_SDK_VERSION = '0.4.57';
68
68
  // Range, not a pin: `castle-web-fonts` is its own package precisely so a tenth
69
69
  // face can ship without a cli release, and a caret range means an existing
70
70
  // deck's next install picks it up. Nothing here has to move when it does.
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Where the serve keeps per-project runtime state: `.castle/runtime/`, which
3
+ * cloud checkpoint capture leaves out (castle-sandboxes checkpointCapture.ts),
4
+ * so these files never block a checkpoint and never travel with the deck.
5
+ */
6
+ export declare const PROJECT_STATE_SEGMENTS: readonly string[];
7
+ /** Where an earlier build of this branch kept the same files (migrated on start). */
8
+ export declare const LEGACY_STATE_SEGMENTS: readonly string[];
9
+ export type StateDir = {
10
+ status: 'ok';
11
+ dir: string;
12
+ } | {
13
+ status: 'missing';
14
+ } | {
15
+ status: 'unsafe';
16
+ reason: string;
17
+ };
18
+ /**
19
+ * The directory `segments` names under `projectDir`, if every component is a
20
+ * real directory (not a symlink). With `create`, missing components are made.
21
+ * `missing` only without `create`; `unsafe` for a symlink or non-directory.
22
+ */
23
+ export declare function projectStateDir(projectDir: string, segments: readonly string[], create: boolean): StateDir;
24
+ /**
25
+ * The text of a small regular file, or null for anything else: missing, a
26
+ * symlink, a FIFO or device (opened non-blocking, so it can never hang the
27
+ * serve), a directory, or larger than `maxBytes`.
28
+ */
29
+ export declare function readSmallStateFile(file: string, maxBytes?: number): string | null;
30
+ /** Whether anything at all (file, link, FIFO...) exists at `file`, without following or opening it. */
31
+ export declare function statePathPresent(file: string): boolean;
32
+ /** Remove a leftover state entry (a file or a symlink; never what a link points at). */
33
+ export declare function removeStateEntry(file: string): boolean;
@@ -0,0 +1,97 @@
1
+ // Small serve state files kept inside a project, which deck code (and anything
2
+ // else that can write the project) can tamper with. Every path is checked
3
+ // component by component below the project root -- a symlinked `.castle` or
4
+ // `.castle/runtime` is refused, never followed -- and a file is opened without
5
+ // following a symlink or blocking on a FIFO, then must be a small regular file.
6
+ import * as fs from 'fs';
7
+ import * as path from 'path';
8
+ /**
9
+ * Where the serve keeps per-project runtime state: `.castle/runtime/`, which
10
+ * cloud checkpoint capture leaves out (castle-sandboxes checkpointCapture.ts),
11
+ * so these files never block a checkpoint and never travel with the deck.
12
+ */
13
+ export const PROJECT_STATE_SEGMENTS = ['.castle', 'runtime'];
14
+ /** Where an earlier build of this branch kept the same files (migrated on start). */
15
+ export const LEGACY_STATE_SEGMENTS = ['.castle'];
16
+ /**
17
+ * The directory `segments` names under `projectDir`, if every component is a
18
+ * real directory (not a symlink). With `create`, missing components are made.
19
+ * `missing` only without `create`; `unsafe` for a symlink or non-directory.
20
+ */
21
+ export function projectStateDir(projectDir, segments, create) {
22
+ let current = projectDir;
23
+ for (const segment of segments) {
24
+ current = path.join(current, segment);
25
+ let stat;
26
+ try {
27
+ stat = fs.lstatSync(current);
28
+ }
29
+ catch (error) {
30
+ if (error.code !== 'ENOENT') {
31
+ return { status: 'unsafe', reason: `cannot inspect ${current}` };
32
+ }
33
+ if (!create)
34
+ return { status: 'missing' };
35
+ try {
36
+ fs.mkdirSync(current);
37
+ stat = fs.lstatSync(current);
38
+ }
39
+ catch (mkdirError) {
40
+ return {
41
+ status: 'unsafe',
42
+ reason: `cannot create ${current}: ${mkdirError instanceof Error ? mkdirError.message : String(mkdirError)}`,
43
+ };
44
+ }
45
+ }
46
+ if (stat.isSymbolicLink())
47
+ return { status: 'unsafe', reason: `${current} is a symlink` };
48
+ if (!stat.isDirectory())
49
+ return { status: 'unsafe', reason: `${current} is not a directory` };
50
+ }
51
+ return { status: 'ok', dir: current };
52
+ }
53
+ /**
54
+ * The text of a small regular file, or null for anything else: missing, a
55
+ * symlink, a FIFO or device (opened non-blocking, so it can never hang the
56
+ * serve), a directory, or larger than `maxBytes`.
57
+ */
58
+ export function readSmallStateFile(file, maxBytes = 4096) {
59
+ let fd = null;
60
+ try {
61
+ fd = fs.openSync(file, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0) | (fs.constants.O_NONBLOCK ?? 0));
62
+ const stat = fs.fstatSync(fd);
63
+ if (!stat.isFile() || stat.size > maxBytes)
64
+ return null;
65
+ return fs.readFileSync(fd, 'utf8');
66
+ }
67
+ catch {
68
+ return null;
69
+ }
70
+ finally {
71
+ if (fd !== null)
72
+ fs.closeSync(fd);
73
+ }
74
+ }
75
+ /** Whether anything at all (file, link, FIFO...) exists at `file`, without following or opening it. */
76
+ export function statePathPresent(file) {
77
+ try {
78
+ fs.lstatSync(file);
79
+ return true;
80
+ }
81
+ catch (error) {
82
+ return error.code !== 'ENOENT';
83
+ }
84
+ }
85
+ /** Remove a leftover state entry (a file or a symlink; never what a link points at). */
86
+ export function removeStateEntry(file) {
87
+ try {
88
+ const stat = fs.lstatSync(file);
89
+ if (stat.isDirectory())
90
+ return false;
91
+ fs.unlinkSync(file);
92
+ return true;
93
+ }
94
+ catch (error) {
95
+ return error.code === 'ENOENT';
96
+ }
97
+ }
package/dist/serve.d.ts CHANGED
@@ -7,10 +7,28 @@ import { DevExperiments } from './devExperiments.js';
7
7
  import { ServeSecurity } from './serveSecurity.js';
8
8
  export declare function appendCapped(file: string, line: string): void;
9
9
  export declare function isViteClientUpgrade(req: http.IncomingMessage): boolean;
10
+ /**
11
+ * True for an address only this machine can reach. Takes the address a server
12
+ * actually bound (`server.address().address`) or a `--host` value; no host means
13
+ * Vite's default, `localhost`.
14
+ */
15
+ export declare function isLoopbackBindHost(host?: string): boolean;
16
+ /**
17
+ * The warning a serve prints when its listener is reachable beyond loopback.
18
+ * `boundAddress` is the address the listener really holds, so a deck's own
19
+ * Vite `server.host` and a hostname `--host` are classified by what they bound.
20
+ * The editor shell hands its browser client the IDE's credentials, terminal
21
+ * included: whoever reaches the port can change the project and run commands.
22
+ * Null on loopback. In a Castle cloud sandbox (CASTLE_SANDBOX_ID) the listener
23
+ * binds every interface of its container on purpose; it says so in one line
24
+ * rather than staying silent, since the variable alone proves nothing.
25
+ */
26
+ export declare function networkExposureWarning(boundAddress: string | undefined, env?: NodeJS.ProcessEnv): string | null;
10
27
  export declare function isAllowedShellHost(hostHeader: string | undefined, configuredHost?: string): boolean;
11
28
  export declare function isAllowedContentFilesRequest(role: 'edit' | 'play' | null, method: string | undefined, reqPath: string): boolean;
12
29
  export declare function injectDeckHead(html: string, play?: boolean): string;
13
30
  export declare function castlePlugin(security: ServeSecurity, ideServer: IdeServer, agentServer: AgentServer, scriptErrors: ScriptErrors, projectDir: string, configuredHost?: string): Plugin;
31
+ export declare const CONTENT_ORIGINS_PATH = "/__castle/content-origins";
14
32
  export declare function devExperimentsFor(projectDir: string): DevExperiments;
15
33
  export declare function serve(dir: string, options?: {
16
34
  port?: string;
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
  }