castle-web-cli 0.4.150 → 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.
- package/dist/agent.d.ts +1 -0
- package/dist/agent.js +12 -4
- package/dist/api.d.ts +33 -3
- package/dist/api.js +17 -3
- package/dist/headlessCover.js +28 -0
- package/dist/native/playtest-remote.d.ts +3 -0
- package/dist/native/playtest-remote.js +113 -0
- package/dist/save-deck.js +22 -5
- package/dist/serve.js +25 -3
- package/dist/serveSecurity.d.ts +2 -0
- package/dist/serveSecurity.js +13 -0
- package/package.json +1 -1
package/dist/agent.d.ts
CHANGED
|
@@ -78,6 +78,7 @@ export declare function createAgentServer(opts: {
|
|
|
78
78
|
deckLabel: string;
|
|
79
79
|
port?: number;
|
|
80
80
|
playtestServeUrl?: string;
|
|
81
|
+
browserContentUrl?: () => string | null;
|
|
81
82
|
restart?: () => void;
|
|
82
83
|
authorizeUpgrade?: (req: http.IncomingMessage, endpoint: 'agent') => boolean;
|
|
83
84
|
}): AgentServer;
|
package/dist/agent.js
CHANGED
|
@@ -36,6 +36,7 @@ import { cancelLogin, logout, startLogin, submitLoginCode } from './byo-login.js
|
|
|
36
36
|
import { runAgentNative } from './native/loop.js';
|
|
37
37
|
import { createPlaytestBrowserManager, } from './native/playtest-browser.js';
|
|
38
38
|
import { createPlaywrightPlaytestExecutor } from './native/playtest-executor.js';
|
|
39
|
+
import { createRemotePlaytestExecutor } from './native/playtest-remote.js';
|
|
39
40
|
export const AGENT_WS_PATH = '/__castle/agent';
|
|
40
41
|
export const AGENT_ATTACHMENT_PREFIX = '/__castle/agent/attachments/';
|
|
41
42
|
// Playtest frame PNGs (tasks/<id>/playtest/<file>.png), served for the
|
|
@@ -3988,10 +3989,15 @@ export function createAgentServer(opts) {
|
|
|
3988
3989
|
// playtest call (each call still gets its own fresh browser context +
|
|
3989
3990
|
// page -- see playtest-executor.ts). Lazily launched on first use; never
|
|
3990
3991
|
// touched at all if no task ever calls playtest.
|
|
3991
|
-
const
|
|
3992
|
+
const remotePlaytest = opts.browserContentUrl
|
|
3993
|
+
? createRemotePlaytestExecutor(opts.browserContentUrl)
|
|
3994
|
+
: null;
|
|
3995
|
+
const playtestBrowserManager = remotePlaytest
|
|
3996
|
+
? null
|
|
3997
|
+
: createPlaytestBrowserManager();
|
|
3992
3998
|
const playtest = opts.port
|
|
3993
3999
|
? {
|
|
3994
|
-
executor: createPlaywrightPlaytestExecutor(playtestBrowserManager),
|
|
4000
|
+
executor: remotePlaytest ?? createPlaywrightPlaytestExecutor(playtestBrowserManager),
|
|
3995
4001
|
// `localhost`, NOT 127.0.0.1: a serve started without --host leaves
|
|
3996
4002
|
// Vite on its default host, which binds ONLY [::1] on macOS --
|
|
3997
4003
|
// 127.0.0.1 never answers there, and playtest would fail every call
|
|
@@ -4001,7 +4007,9 @@ export function createAgentServer(opts) {
|
|
|
4001
4007
|
// Kicks off the one-time Chromium download in the background at
|
|
4002
4008
|
// smith-task start (see runTaskAgentIn) -- single-flight with any
|
|
4003
4009
|
// real playtest call, silent on every failure path.
|
|
4004
|
-
prewarm:
|
|
4010
|
+
prewarm: playtestBrowserManager
|
|
4011
|
+
? () => playtestBrowserManager.prewarm()
|
|
4012
|
+
: undefined,
|
|
4005
4013
|
}
|
|
4006
4014
|
: undefined;
|
|
4007
4015
|
const taskChildren = new Set();
|
|
@@ -4246,7 +4254,7 @@ export function createAgentServer(opts) {
|
|
|
4246
4254
|
usageFeed.stop();
|
|
4247
4255
|
accountsFeed.stop();
|
|
4248
4256
|
wss.close();
|
|
4249
|
-
void playtestBrowserManager
|
|
4257
|
+
void playtestBrowserManager?.shutdown();
|
|
4250
4258
|
}
|
|
4251
4259
|
return { handleUpgrade, handleHttpRequest, shutdown };
|
|
4252
4260
|
}
|
package/dist/api.d.ts
CHANGED
|
@@ -5,7 +5,33 @@ interface GraphqlResponse {
|
|
|
5
5
|
extensions?: Record<string, unknown>;
|
|
6
6
|
}>;
|
|
7
7
|
}
|
|
8
|
-
export declare function graphql(query: string, variables?: Record<string, unknown
|
|
8
|
+
export declare function graphql(query: string, variables?: Record<string, unknown>, options?: {
|
|
9
|
+
timeoutMs?: number;
|
|
10
|
+
signal?: AbortSignal;
|
|
11
|
+
}): Promise<GraphqlResponse>;
|
|
12
|
+
export type BrowserOperation = {
|
|
13
|
+
kind: 'playtest';
|
|
14
|
+
durationMs: number;
|
|
15
|
+
actions: Array<{
|
|
16
|
+
t: number;
|
|
17
|
+
type: 'down' | 'move' | 'up' | 'tap' | 'key';
|
|
18
|
+
x?: number;
|
|
19
|
+
y?: number;
|
|
20
|
+
key?: string;
|
|
21
|
+
durationMs?: number;
|
|
22
|
+
}>;
|
|
23
|
+
screenshots: number[];
|
|
24
|
+
} | {
|
|
25
|
+
kind: 'cover';
|
|
26
|
+
};
|
|
27
|
+
export interface BrowserJobResult {
|
|
28
|
+
protocolVersion: number;
|
|
29
|
+
jobId: string;
|
|
30
|
+
operation: 'playtest' | 'cover';
|
|
31
|
+
ok: boolean;
|
|
32
|
+
[key: string]: unknown;
|
|
33
|
+
}
|
|
34
|
+
export declare function runBrowserJob(contentGrant: string, operation: BrowserOperation, signal?: AbortSignal): Promise<BrowserJobResult>;
|
|
9
35
|
export declare function startCLILogin(): Promise<{
|
|
10
36
|
pollToken: string;
|
|
11
37
|
url: string;
|
|
@@ -103,9 +129,13 @@ export interface CauldronServerConfig {
|
|
|
103
129
|
tickRate: number;
|
|
104
130
|
maxPlayers: number;
|
|
105
131
|
}
|
|
106
|
-
export
|
|
132
|
+
export interface CauldronServerBundleResult {
|
|
107
133
|
deckId: string;
|
|
108
|
-
|
|
134
|
+
version: string;
|
|
135
|
+
sha256: string;
|
|
136
|
+
sizeBytes: number;
|
|
137
|
+
}
|
|
138
|
+
export declare function saveCauldronServerBundle(deckId: string, uploadId: string | null, serverConfig?: CauldronServerConfig): Promise<CauldronServerBundleResult | null>;
|
|
109
139
|
export interface WebDeckSource {
|
|
110
140
|
deckId: string;
|
|
111
141
|
archiveUrl: string;
|
package/dist/api.js
CHANGED
|
@@ -3,7 +3,7 @@ import * as config from './config.js';
|
|
|
3
3
|
// sandboxes (which also set CASTLE_TOKEN to a sandbox-scoped credential). Unset anywhere
|
|
4
4
|
// else, so normal installs always talk to the real API.
|
|
5
5
|
const API_HOST = process.env.CASTLE_API_URL || 'https://api.castle.xyz/graphql';
|
|
6
|
-
export async function graphql(query, variables) {
|
|
6
|
+
export async function graphql(query, variables, options = {}) {
|
|
7
7
|
const token = config.getToken();
|
|
8
8
|
const headers = {
|
|
9
9
|
'X-OS': 'cli',
|
|
@@ -13,14 +13,25 @@ export async function graphql(query, variables) {
|
|
|
13
13
|
};
|
|
14
14
|
if (token)
|
|
15
15
|
headers['X-Auth-Token'] = token;
|
|
16
|
+
const timeoutSignal = AbortSignal.timeout(options.timeoutMs ?? 10_000);
|
|
17
|
+
const signal = options.signal
|
|
18
|
+
? AbortSignal.any([timeoutSignal, options.signal])
|
|
19
|
+
: timeoutSignal;
|
|
16
20
|
const res = await fetch(API_HOST, {
|
|
17
21
|
method: 'POST',
|
|
18
22
|
headers,
|
|
19
23
|
body: JSON.stringify(variables ? { query, variables } : { query }),
|
|
20
|
-
signal
|
|
24
|
+
signal,
|
|
21
25
|
});
|
|
22
26
|
return res.json();
|
|
23
27
|
}
|
|
28
|
+
export async function runBrowserJob(contentGrant, operation, signal) {
|
|
29
|
+
const data = await graphql(`mutation($contentGrant: String!, $operation: Json!) {
|
|
30
|
+
runBrowserJob(contentGrant: $contentGrant, operation: $operation)
|
|
31
|
+
}`, { contentGrant, operation }, { timeoutMs: 85_000, signal });
|
|
32
|
+
handleAPIError(data);
|
|
33
|
+
return pickData(data, 'runBrowserJob');
|
|
34
|
+
}
|
|
24
35
|
// Castle masks every ClientError's message to "Unexpected error." and puts the
|
|
25
36
|
// real one in `extensions.code` -- so the bare message is the same string for a
|
|
26
37
|
// permissions failure, a missing deck, and a bad argument. Carry the code in the
|
|
@@ -213,9 +224,12 @@ export async function createCauldronServerBundleUploadConfig(deckId) {
|
|
|
213
224
|
return pickData(data, 'createCauldronServerBundleUploadConfig');
|
|
214
225
|
}
|
|
215
226
|
export async function saveCauldronServerBundle(deckId, uploadId, serverConfig) {
|
|
216
|
-
const data = await graphql(`mutation($deckId: ID!, $uploadId:
|
|
227
|
+
const data = await graphql(`mutation($deckId: ID!, $uploadId: String, $config: Json) {
|
|
217
228
|
saveCauldronServerBundle(deckId: $deckId, uploadId: $uploadId, config: $config) {
|
|
218
229
|
deckId
|
|
230
|
+
version
|
|
231
|
+
sha256
|
|
232
|
+
sizeBytes
|
|
219
233
|
}
|
|
220
234
|
}`, { deckId, uploadId, ...(serverConfig ? { config: serverConfig } : {}) });
|
|
221
235
|
handleAPIError(data);
|
package/dist/headlessCover.js
CHANGED
|
@@ -22,6 +22,8 @@
|
|
|
22
22
|
import fs from "fs";
|
|
23
23
|
import path from "path";
|
|
24
24
|
import { createPlaytestBrowserManager } from "./native/playtest-browser.js";
|
|
25
|
+
import * as api from "./api.js";
|
|
26
|
+
import { contentGrantFromBrowserUrl } from "./native/playtest-remote.js";
|
|
25
27
|
// The card is 5:7; this is the same fixed viewport the playtest tool uses, so a
|
|
26
28
|
// deck laid out for one is laid out for the other.
|
|
27
29
|
const VIEWPORT = { width: 500, height: 700 };
|
|
@@ -46,6 +48,10 @@ const CARD_SELECTOR = "#castle-card, [data-castle-card]";
|
|
|
46
48
|
// Grab the deck's cover from `serveUrl` and write it to `<projectDir>/.castle`.
|
|
47
49
|
// Never throws; a failure is reported, not raised.
|
|
48
50
|
export async function captureCoverHeadless(opts) {
|
|
51
|
+
const remoteGrant = contentGrantFromBrowserUrl(opts.serveUrl);
|
|
52
|
+
if (remoteGrant) {
|
|
53
|
+
return captureCoverRemote(remoteGrant, opts.outPath);
|
|
54
|
+
}
|
|
49
55
|
// A manager we made is a manager we must close. `withBrowser` deliberately
|
|
50
56
|
// leaves the browser RUNNING so the next call reuses it -- right for the
|
|
51
57
|
// agent, which holds one manager for its whole session, and fatal here:
|
|
@@ -84,6 +90,28 @@ export async function captureCoverHeadless(opts) {
|
|
|
84
90
|
await manager.shutdown().catch(() => undefined);
|
|
85
91
|
}
|
|
86
92
|
}
|
|
93
|
+
async function captureCoverRemote(contentGrant, outPath) {
|
|
94
|
+
try {
|
|
95
|
+
const result = await api.runBrowserJob(contentGrant, { kind: 'cover' });
|
|
96
|
+
const pngBase64 = result.pngBase64;
|
|
97
|
+
if (result.protocolVersion !== 1 ||
|
|
98
|
+
result.operation !== 'cover' ||
|
|
99
|
+
!result.ok ||
|
|
100
|
+
typeof pngBase64 !== 'string') {
|
|
101
|
+
const error = typeof result.error === 'string' ? result.error : 'browser worker returned an invalid cover';
|
|
102
|
+
return { ok: false, error };
|
|
103
|
+
}
|
|
104
|
+
const png = Buffer.from(pngBase64, 'base64');
|
|
105
|
+
if (png.length === 0)
|
|
106
|
+
return { ok: false, error: 'browser worker returned an empty cover' };
|
|
107
|
+
fs.mkdirSync(path.dirname(outPath), { recursive: true });
|
|
108
|
+
fs.writeFileSync(outPath, png);
|
|
109
|
+
return { ok: true, outPath };
|
|
110
|
+
}
|
|
111
|
+
catch (error) {
|
|
112
|
+
return { ok: false, error: error instanceof Error ? error.message : String(error) };
|
|
113
|
+
}
|
|
114
|
+
}
|
|
87
115
|
// Resolve with `work`, or with null if the budget runs out first. The loser is
|
|
88
116
|
// abandoned rather than cancelled -- the shutdown in the caller's `finally` is
|
|
89
117
|
// what actually stops the browser it was using.
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import * as api from '../api.js';
|
|
2
|
+
import { PLAYTEST_VIEWPORT, } from './playtest.js';
|
|
3
|
+
const CONTENT_HOST_RE = /^(?<grant>[a-z0-9-]{1,63})\.sandboxes(?:-staging)?\.castlexyz\.com$/;
|
|
4
|
+
function failed(input, error) {
|
|
5
|
+
return {
|
|
6
|
+
ok: false,
|
|
7
|
+
error,
|
|
8
|
+
viewport: PLAYTEST_VIEWPORT,
|
|
9
|
+
frames: [],
|
|
10
|
+
console: [],
|
|
11
|
+
diagnostics: {
|
|
12
|
+
rafTicks: 0,
|
|
13
|
+
wallMs: 0,
|
|
14
|
+
framesRequested: input.timeline.filter((event) => event.kind === 'screenshot').length,
|
|
15
|
+
framesCaptured: 0,
|
|
16
|
+
hidden: false,
|
|
17
|
+
},
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
export function contentGrantFromBrowserUrl(value) {
|
|
21
|
+
try {
|
|
22
|
+
const url = new URL(value);
|
|
23
|
+
if (url.protocol !== 'https:')
|
|
24
|
+
return null;
|
|
25
|
+
return CONTENT_HOST_RE.exec(url.hostname)?.groups?.grant ?? null;
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
return null;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
function operationFromTimeline(input) {
|
|
32
|
+
const actions = [];
|
|
33
|
+
const screenshots = [];
|
|
34
|
+
const keyDown = new Map();
|
|
35
|
+
for (const event of input.timeline) {
|
|
36
|
+
if (event.kind === 'screenshot') {
|
|
37
|
+
screenshots.push(event.t);
|
|
38
|
+
}
|
|
39
|
+
else if (event.kind === 'keydown') {
|
|
40
|
+
const times = keyDown.get(event.key) ?? [];
|
|
41
|
+
times.push(event.t);
|
|
42
|
+
keyDown.set(event.key, times);
|
|
43
|
+
}
|
|
44
|
+
else if (event.kind === 'keyup') {
|
|
45
|
+
const times = keyDown.get(event.key);
|
|
46
|
+
const startedAt = times?.shift();
|
|
47
|
+
if (startedAt !== undefined) {
|
|
48
|
+
actions.push({
|
|
49
|
+
t: startedAt,
|
|
50
|
+
type: 'key',
|
|
51
|
+
key: event.key,
|
|
52
|
+
durationMs: event.t - startedAt,
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
else {
|
|
57
|
+
if (!('x' in event))
|
|
58
|
+
continue;
|
|
59
|
+
actions.push({
|
|
60
|
+
t: event.t,
|
|
61
|
+
type: event.kind === 'mousedown'
|
|
62
|
+
? 'down'
|
|
63
|
+
: event.kind === 'mouseup'
|
|
64
|
+
? 'up'
|
|
65
|
+
: 'move',
|
|
66
|
+
x: event.x,
|
|
67
|
+
y: event.y,
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
actions.sort((a, b) => a.t - b.t);
|
|
72
|
+
return { kind: 'playtest', durationMs: input.durationMs, actions, screenshots };
|
|
73
|
+
}
|
|
74
|
+
function validRemoteResult(result) {
|
|
75
|
+
return (result.protocolVersion === 1 &&
|
|
76
|
+
result.operation === 'playtest' &&
|
|
77
|
+
result.ok === true &&
|
|
78
|
+
result.viewport?.width === PLAYTEST_VIEWPORT.width &&
|
|
79
|
+
result.viewport?.height === PLAYTEST_VIEWPORT.height &&
|
|
80
|
+
Array.isArray(result.frames) &&
|
|
81
|
+
Array.isArray(result.console) &&
|
|
82
|
+
Boolean(result.diagnostics));
|
|
83
|
+
}
|
|
84
|
+
export function createRemotePlaytestExecutor(browserContentUrl) {
|
|
85
|
+
return {
|
|
86
|
+
async runSession(input) {
|
|
87
|
+
const contentUrl = browserContentUrl();
|
|
88
|
+
const grant = contentUrl ? contentGrantFromBrowserUrl(contentUrl) : null;
|
|
89
|
+
if (!grant)
|
|
90
|
+
return failed(input, 'the serve could not mint a browser content grant');
|
|
91
|
+
try {
|
|
92
|
+
const result = (await api.runBrowserJob(grant, operationFromTimeline(input), input.signal));
|
|
93
|
+
if (!result.ok)
|
|
94
|
+
return failed(input, result.error ?? 'browser worker failed');
|
|
95
|
+
if (!validRemoteResult(result))
|
|
96
|
+
return failed(input, 'browser worker returned an invalid result');
|
|
97
|
+
return {
|
|
98
|
+
ok: true,
|
|
99
|
+
viewport: result.viewport,
|
|
100
|
+
frames: result.frames.map((frame) => ({
|
|
101
|
+
t: frame.t,
|
|
102
|
+
png: Buffer.from(frame.pngBase64, 'base64'),
|
|
103
|
+
})),
|
|
104
|
+
console: result.console,
|
|
105
|
+
diagnostics: result.diagnostics,
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
catch (error) {
|
|
109
|
+
return failed(input, error instanceof Error ? error.message : String(error));
|
|
110
|
+
}
|
|
111
|
+
},
|
|
112
|
+
};
|
|
113
|
+
}
|
package/dist/save-deck.js
CHANGED
|
@@ -122,12 +122,18 @@ async function publishServerBundle(projectDir, deckId) {
|
|
|
122
122
|
console.log(`Server bundle size: ${(bundle.sizeBytes / 1024).toFixed(1)}KB`);
|
|
123
123
|
const uploadConfig = await api.createCauldronServerBundleUploadConfig(deckId);
|
|
124
124
|
await uploadPresignedFile(uploadConfig, new Blob([bundle.code], { type: 'application/javascript' }), 'application/javascript', 60_000, 'Server bundle upload');
|
|
125
|
-
await api.saveCauldronServerBundle(deckId, uploadConfig.uploadId, {
|
|
125
|
+
const saved = await api.saveCauldronServerBundle(deckId, uploadConfig.uploadId, {
|
|
126
126
|
tickRate: serverConfig.tickRate,
|
|
127
127
|
maxPlayers: serverConfig.maxPlayers,
|
|
128
128
|
});
|
|
129
|
+
// The server hashes what it actually stored. A mismatch means the bytes that
|
|
130
|
+
// will run in sessions are not the bytes we bundled.
|
|
131
|
+
if (saved && saved.sha256 !== bundle.sha256) {
|
|
132
|
+
throw new Error(`Published server bundle does not match what was built ` +
|
|
133
|
+
`(server ${saved.sha256}, local ${bundle.sha256}). The deck was not updated safely.`);
|
|
134
|
+
}
|
|
129
135
|
writePublishedServerBundleState(projectDir, { deckId, sha256: bundle.sha256 });
|
|
130
|
-
console.log(`Server bundle published (sha256 ${bundle.sha256}).`);
|
|
136
|
+
console.log(`Server bundle published${saved ? ` as ${saved.version}` : ''} (sha256 ${bundle.sha256}).`);
|
|
131
137
|
}
|
|
132
138
|
// Publish the deck's local cover, if it has one, and return the file id for the
|
|
133
139
|
// card. The editor writes `preview.png` as you play (see the serve's cover
|
|
@@ -138,13 +144,24 @@ async function publishServerBundle(projectDir, deckId) {
|
|
|
138
144
|
// The deck's own serve, if one is running -- the URL a headless cover capture
|
|
139
145
|
// loads. No serve means no deck to photograph, which is a normal state (a save
|
|
140
146
|
// from a script), not an error.
|
|
141
|
-
function runningServeUrl(projectDir) {
|
|
147
|
+
async function runningServeUrl(projectDir) {
|
|
142
148
|
try {
|
|
143
149
|
const raw = fs.readFileSync(path.join(projectDir, '.castle', 'serve.json'), 'utf8');
|
|
144
150
|
const parsed = JSON.parse(raw);
|
|
151
|
+
const port = parsed.port;
|
|
152
|
+
if (process.env.CASTLE_SANDBOX_ID && typeof port === 'number') {
|
|
153
|
+
try {
|
|
154
|
+
const response = await fetch(`http://localhost:${port}/__castle/browser-content-grant`, { signal: AbortSignal.timeout(2_000) });
|
|
155
|
+
const body = (await response.json());
|
|
156
|
+
if (response.ok && typeof body.url === 'string')
|
|
157
|
+
return body.url;
|
|
158
|
+
}
|
|
159
|
+
catch {
|
|
160
|
+
// Fall through to the existing best-effort local capture path.
|
|
161
|
+
}
|
|
162
|
+
}
|
|
145
163
|
if (typeof parsed.contentPlayUrl === 'string')
|
|
146
164
|
return parsed.contentPlayUrl;
|
|
147
|
-
const port = parsed.port;
|
|
148
165
|
return typeof port === 'number' ? `http://localhost:${port}` : null;
|
|
149
166
|
}
|
|
150
167
|
catch {
|
|
@@ -166,7 +183,7 @@ function runningServeUrl(projectDir) {
|
|
|
166
183
|
// you never look at it, and nobody looks at an unattended capture. Writing to a
|
|
167
184
|
// scratch file rather than over `preview.png` keeps that fallback intact.
|
|
168
185
|
async function captureAutomaticCover(projectDir) {
|
|
169
|
-
const serveUrl = runningServeUrl(projectDir);
|
|
186
|
+
const serveUrl = await runningServeUrl(projectDir);
|
|
170
187
|
if (!serveUrl)
|
|
171
188
|
return null;
|
|
172
189
|
const outPath = path.join(projectDir, '.castle', 'headless-cover.png');
|
package/dist/serve.js
CHANGED
|
@@ -299,6 +299,23 @@ window.__castleShellOrigin=(function(){
|
|
|
299
299
|
res.writeHead(403).end('untrusted host');
|
|
300
300
|
return;
|
|
301
301
|
}
|
|
302
|
+
if (reqPath === '/__castle/browser-content-grant') {
|
|
303
|
+
if (content || req.method !== 'GET') {
|
|
304
|
+
res.writeHead(403).end();
|
|
305
|
+
return;
|
|
306
|
+
}
|
|
307
|
+
const url = security.browserContentOrigin('play');
|
|
308
|
+
if (!url) {
|
|
309
|
+
res.writeHead(404).end();
|
|
310
|
+
return;
|
|
311
|
+
}
|
|
312
|
+
res.writeHead(200, {
|
|
313
|
+
'content-type': 'application/json',
|
|
314
|
+
'cache-control': 'no-store',
|
|
315
|
+
});
|
|
316
|
+
res.end(JSON.stringify({ url }));
|
|
317
|
+
return;
|
|
318
|
+
}
|
|
302
319
|
if (reqPath === '/__castle/ws-ticket') {
|
|
303
320
|
if (content || req.method !== 'POST') {
|
|
304
321
|
res.writeHead(403).end();
|
|
@@ -581,9 +598,11 @@ export async function serve(dir, options = {}) {
|
|
|
581
598
|
// playtest tool, so this is free when that already pulled it, and every
|
|
582
599
|
// failure is swallowed -- the capture re-detects and reports properly at the
|
|
583
600
|
// point it actually matters.
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
601
|
+
if (!process.env.CASTLE_SANDBOX_ID) {
|
|
602
|
+
void import('./native/playtest-browser.js')
|
|
603
|
+
.then((m) => m.createPlaytestBrowserManager().prewarm())
|
|
604
|
+
.catch(() => undefined);
|
|
605
|
+
}
|
|
587
606
|
// Close stdin when not attached to a TTY so the process can be cleanly
|
|
588
607
|
// backgrounded with `&` (otherwise stdin reads can block or hold the parent).
|
|
589
608
|
if (!process.stdin.isTTY) {
|
|
@@ -690,6 +709,9 @@ export async function serve(dir, options = {}) {
|
|
|
690
709
|
deckLabel: path.basename(projectDir),
|
|
691
710
|
port,
|
|
692
711
|
playtestServeUrl: security.localContentOrigin('play'),
|
|
712
|
+
browserContentUrl: process.env.CASTLE_SANDBOX_ID
|
|
713
|
+
? () => security.browserContentOrigin('play')
|
|
714
|
+
: undefined,
|
|
693
715
|
// Same effect as the WS server's own 'restart' branch below (invalidate
|
|
694
716
|
// then tell every connected tab to reload), called directly in-process
|
|
695
717
|
// instead of round-tripping through a WebSocket message -- this is what
|
package/dist/serveSecurity.d.ts
CHANGED
|
@@ -33,6 +33,8 @@ export declare class ServeSecurity {
|
|
|
33
33
|
playOrigin: string;
|
|
34
34
|
};
|
|
35
35
|
localContentOrigin(role: ContentRole): string;
|
|
36
|
+
/** A short-lived play URL for one shared-browser admission attempt. */
|
|
37
|
+
browserContentOrigin(role?: ContentRole): string | null;
|
|
36
38
|
localContentProxyHeaders(role: ContentRole): Record<string, string>;
|
|
37
39
|
verifyContentRequest(req: http.IncomingMessage): ContentRole | null;
|
|
38
40
|
compatibilityContentRole(req: http.IncomingMessage): ContentRole | null;
|
package/dist/serveSecurity.js
CHANGED
|
@@ -5,6 +5,7 @@ const CROCKFORD = '0123456789abcdefghjkmnpqrstvwxyz';
|
|
|
5
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})$/;
|
|
6
6
|
const MAX_GRANT_SECONDS = 12 * 60 * 60;
|
|
7
7
|
const GRANT_CLOCK_SKEW_SECONDS = 60;
|
|
8
|
+
const BROWSER_GRANT_SECONDS = 3 * 60;
|
|
8
9
|
export const MOBILE_HOST_PROTOCOL = '2';
|
|
9
10
|
function base32Lower(bytes) {
|
|
10
11
|
let bits = 0;
|
|
@@ -209,6 +210,18 @@ window.fetch=function(input,init){
|
|
|
209
210
|
throw new Error('local content ports are not configured');
|
|
210
211
|
return `http://127.0.0.1:${port}`;
|
|
211
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}`;
|
|
224
|
+
}
|
|
212
225
|
localContentProxyHeaders(role) {
|
|
213
226
|
return {
|
|
214
227
|
'x-castle-content-role': role,
|