castle-web-cli 0.4.243 → 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 +1 -0
- package/dist/api.js +13 -0
- package/dist/contentOriginTiming.d.ts +13 -0
- package/dist/contentOriginTiming.js +15 -0
- package/dist/imports.js +28 -6
- package/dist/index.js +54 -5
- package/dist/init.js +1 -1
- package/dist/projectState.d.ts +33 -0
- package/dist/projectState.js +97 -0
- package/dist/serve.d.ts +18 -0
- package/dist/serve.js +103 -2
- package/dist/serveSecurity.d.ts +105 -3
- package/dist/serveSecurity.js +500 -39
- package/dist/shell/assets/{index-DulbYIJm.js → index-Bec6LpAv.js} +87 -87
- package/dist/shell/index.html +1 -1
- package/kits/base/castle.json +1 -1
- package/kits/base/sdk/runtime.js +57 -0
- package/kits/hub-game/code/client/chrome.js +9 -2
- package/kits/hub-game/code/client/hookLayer.js +8 -0
- package/kits/hub-game/code/client/padCues.js +2 -0
- package/kits/hub-game/code/client/padReadability.js +6 -1
- package/kits/hub-game/code/client/signals.js +126 -0
- package/kits/hub-game/code/client/state.js +4 -0
- package/kits/hub-game/code/server/friendBests.js +8 -2
- package/kits/hub-game/code/server/hub.js +31 -4
- package/kits/hub-game/code/server/npcs.js +4 -0
- package/kits/hub-game/code/server/party.js +3 -0
- package/kits/hub-game/code/server/resumePose.js +30 -9
- package/kits/hub-game/code/server/signals.js +124 -0
- package/kits/hub-game/code/server/writerLease.js +161 -17
- package/kits/hub-game/code/systems/hub.js +21 -2
- package/kits/hub-game/docs/contract.md +92 -11
- package/kits/hub-game/package.json +1 -1
- package/kits/hub-game/scripts/test-menu-client.mjs +7 -6
- package/kits/hub-game/scripts/test-menu-footer-dom.mjs +94 -0
- package/kits/hub-game/scripts/test-pad-cues.mjs +6 -3
- package/kits/hub-game/scripts/test-resume-pose.mjs +85 -0
- package/kits/hub-game/scripts/test-signals.mjs +412 -0
- package/kits/hub-game/scripts/test-writer-lease-server.mjs +108 -4
- package/kits/hub-game/scripts/test-writer-lease.mjs +385 -1
- package/package.json +2 -2
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
|
-
|
|
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
|
-
//
|
|
540
|
-
//
|
|
541
|
-
//
|
|
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
|
|
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
|
@@ -175,7 +175,7 @@ function availableKits() {
|
|
|
175
175
|
return FALLBACK_KITS;
|
|
176
176
|
}
|
|
177
177
|
}
|
|
178
|
-
function
|
|
178
|
+
function usageText() {
|
|
179
179
|
const kits = availableKits();
|
|
180
180
|
const scaffoldKits = kits.filter((kit) => kit !== 'base' && kit !== 'real-time');
|
|
181
181
|
const initKits = [...scaffoldKits, 'none'].join(', ');
|
|
@@ -184,10 +184,10 @@ function usage() {
|
|
|
184
184
|
...kits.map((kit) => ` ${kit.padEnd(kitNameWidth)} ${KIT_DESCRIPTIONS[kit] ?? 'Scaffold kit.'}`),
|
|
185
185
|
` ${'none'.padEnd(kitNameWidth)} Minimal vite + canvas setup with the castle-web SDK and no kit.`,
|
|
186
186
|
].join('\n');
|
|
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)
|
|
@@ -225,9 +225,29 @@ function usage() {
|
|
|
225
225
|
Kits:
|
|
226
226
|
${kitLines}
|
|
227
227
|
|
|
228
|
-
After init, read the scaffolded deck's CLAUDE.md (also AGENTS.md) for the kit's full author guide
|
|
228
|
+
After init, read the scaffolded deck's CLAUDE.md (also AGENTS.md) for the kit's full author guide.`;
|
|
229
|
+
}
|
|
230
|
+
function usage() {
|
|
231
|
+
console.log(usageText());
|
|
229
232
|
process.exit(1);
|
|
230
233
|
}
|
|
234
|
+
// `--help` / `-h` anywhere among a command's arguments -- after a `--`, or where a flag
|
|
235
|
+
// expects its value, too. Commands parse loosely (most ignore flags they don't take, and
|
|
236
|
+
// `--` is dropped before positionals are read), so any exception lets one through to the
|
|
237
|
+
// action; a literal path or value spelled `--help` is not worth that.
|
|
238
|
+
function wantsHelp() {
|
|
239
|
+
return args.slice(1).some((arg) => arg === '--help' || arg === '-h');
|
|
240
|
+
}
|
|
241
|
+
// The usage lines for `command` (and `git <sub>`), or the whole text when it has none.
|
|
242
|
+
function helpText() {
|
|
243
|
+
const text = usageText();
|
|
244
|
+
const sub = command === 'git' ? readPositionals()[0] : undefined;
|
|
245
|
+
const prefix = sub && !sub.startsWith('-') ? `castle-web git ${sub} ` : `castle-web ${command} `;
|
|
246
|
+
const lines = text.split('\n').filter((line) => line.trimStart().startsWith(prefix));
|
|
247
|
+
if (lines.length === 0)
|
|
248
|
+
return text;
|
|
249
|
+
return `Usage:\n${lines.join('\n')}`;
|
|
250
|
+
}
|
|
231
251
|
// `git init`'s own arguments, strictly: an unknown flag is an error rather than
|
|
232
252
|
// ignored, since a typo'd `--staging` would otherwise target production.
|
|
233
253
|
function parseGitInitArgs() {
|
|
@@ -529,6 +549,17 @@ async function main() {
|
|
|
529
549
|
console.log(getCliVersion());
|
|
530
550
|
return;
|
|
531
551
|
}
|
|
552
|
+
// Also before the switch, and before any command reads its arguments: no command
|
|
553
|
+
// knows --help, and most skip an unknown flag and run -- `save-deck --help` saved
|
|
554
|
+
// the deck. Asking for help never does anything else.
|
|
555
|
+
if (command === '--help' || command === '-h' || command === 'help') {
|
|
556
|
+
console.log(usageText());
|
|
557
|
+
return;
|
|
558
|
+
}
|
|
559
|
+
if (wantsHelp()) {
|
|
560
|
+
console.log(helpText());
|
|
561
|
+
return;
|
|
562
|
+
}
|
|
532
563
|
if (VERSION_COMMANDS.has(command) && (await gitVersionCommand(command)))
|
|
533
564
|
return;
|
|
534
565
|
switch (command) {
|
|
@@ -554,7 +585,25 @@ async function main() {
|
|
|
554
585
|
case 'serve': {
|
|
555
586
|
const dir = findPositionalDir();
|
|
556
587
|
const port = getFlagValue('--port');
|
|
557
|
-
|
|
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
|
+
}
|
|
558
607
|
const open = args.includes('--open');
|
|
559
608
|
const detach = args.includes('--detach');
|
|
560
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.
|
|
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
|
|
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}`);
|