castle-web-cli 0.4.244 → 0.4.246

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,9 @@
1
1
  import { createHmac, randomBytes, timingSafeEqual } from 'crypto';
2
+ import * as fs from 'fs';
3
+ import * as path from 'path';
4
+ import { atomicWriteFileSync } from './atomicFile.js';
5
+ import { LEGACY_STATE_SEGMENTS, PROJECT_STATE_SEGMENTS, projectStateDir, readSmallStateFile, removeStateEntry, statePathPresent, } from './projectState.js';
6
+ import { MIN_CONTENT_GRANT_REMAINING_SECONDS } from './contentOriginTiming.js';
2
7
  import { AGENT_ATTACHMENT_PREFIX, AGENT_PLAYTEST_PREFIX } from './localPaths.js';
3
8
  export const SERVE_AUTH_FAILURE_HEADER = 'x-castle-serve-auth';
4
9
  export const SERVE_AUTH_FAILURE_VALUE = 'invalid';
@@ -6,9 +11,172 @@ const CROCKFORD = '0123456789abcdefghjkmnpqrstvwxyz';
6
11
  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})$/;
7
12
  const MAX_GRANT_SECONDS = 12 * 60 * 60;
8
13
  const GRANT_CLOCK_SKEW_SECONDS = 60;
9
- const MIN_CONTENT_GRANT_REMAINING_SECONDS = 11 * 60 * 60;
10
14
  const BROWSER_GRANT_SECONDS = 3 * 60;
11
15
  export const MOBILE_HOST_PROTOCOL = '2';
16
+ // Query parameter a compatibility-mode shell puts on its own frame URLs. It
17
+ // proves the `/index.html` request came from a shell this serve put into
18
+ // compatibility mode, so deck code running on an isolated content origin cannot
19
+ // open the editor origin's compatibility route and run itself beside the shell.
20
+ export const COMPAT_CONTENT_PARAM = 'castleCompat';
21
+ // Under the project's `.castle/runtime/` (projectState.ts): present once any
22
+ // protocol-2 app shell has opened this project. Deleting it is the only reset.
23
+ export const PROTOCOL2_MARKER_FILE = 'protocol2-shell-seen.json';
24
+ // Under the project's `.castle/runtime/`: the project id and grant expiry
25
+ // every serve of this project derives its content hostnames from, so a
26
+ // restarted serve keeps the same edit/play origins (and the localStorage on
27
+ // them, such as the SDK's save queue) and still verifies the labels its
28
+ // predecessor handed out.
29
+ export const CONTENT_ORIGIN_FILE = 'content-origin.json';
30
+ const PROJECT_ID_RE = /^[0-9a-hjkmnp-tv-z]{26}$/;
31
+ // A request to a static deck path that names one of these is a document load:
32
+ // in compatibility mode a referrer-less one never gets a content role.
33
+ const DOCUMENT_FETCH_DESTS = new Set([
34
+ 'document',
35
+ 'iframe',
36
+ 'frame',
37
+ 'embed',
38
+ 'object',
39
+ 'fencedframe',
40
+ ]);
41
+ /** A content-origin record, or null for anything that is not a well-formed one. */
42
+ function parseContentOriginRecord(text) {
43
+ if (text === null)
44
+ return null;
45
+ try {
46
+ const parsed = JSON.parse(text);
47
+ if (!parsed ||
48
+ parsed.version !== 2 ||
49
+ typeof parsed.projectId !== 'string' ||
50
+ !PROJECT_ID_RE.test(parsed.projectId) ||
51
+ typeof parsed.expiresAtSeconds !== 'number' ||
52
+ !Number.isSafeInteger(parsed.expiresAtSeconds) ||
53
+ parsed.expiresAtSeconds < 0) {
54
+ return null;
55
+ }
56
+ return { version: 2, projectId: parsed.projectId, expiresAtSeconds: parsed.expiresAtSeconds };
57
+ }
58
+ catch {
59
+ return null;
60
+ }
61
+ }
62
+ // What may refer onward in compatibility mode: deck HTML documents and JS
63
+ // modules (Vite's own `/@vite/`, `/@id/` modules have no extension). Never a
64
+ // static asset.
65
+ const ONWARD_REFERRER_EXT_RE = /\.(?:html?|m?js|cjs|jsx|tsx?|mts|cts|vue|svelte)$/i;
66
+ function mayReferOnward(pathname) {
67
+ const last = pathname.slice(pathname.lastIndexOf('/') + 1);
68
+ if (!last.includes('.'))
69
+ return pathname.startsWith('/@');
70
+ return ONWARD_REFERRER_EXT_RE.test(last);
71
+ }
72
+ /**
73
+ * The path Vite will actually serve for a request pathname: percent-decoded
74
+ * (as Vite decodes it) and normalized, so classification cannot be dodged by
75
+ * encoding (`/%40fs/...svg`, `/%69ndex.html`). Null when it does not decode.
76
+ */
77
+ function servedPathname(pathname) {
78
+ let decoded;
79
+ try {
80
+ decoded = decodeURIComponent(pathname);
81
+ }
82
+ catch {
83
+ return null;
84
+ }
85
+ if (decoded.includes('\0'))
86
+ return null;
87
+ const normalized = path.posix.normalize(decoded);
88
+ return normalized.startsWith('/') ? normalized : `/${normalized}`;
89
+ }
90
+ /**
91
+ * A `no-referrer` deck's own static loads (its entry module, CSS, images),
92
+ * which main served with the play role, and the loads of a static-asset
93
+ * referrer (a stylesheet's fonts). Fetch-Metadata requests only: a document
94
+ * load gets no role; a subresource gets the play role and a sandboxed
95
+ * response (CSP `sandbox`, nosniff, no Vite HTML fallback -- see serve.ts),
96
+ * so even a document that renders one runs on an opaque origin. Subresource
97
+ * loads ignore a response's CSP, so decks work as on main. `/__castle/`
98
+ * never gets a role.
99
+ */
100
+ function referrerlessStaticContent(dest, pathname) {
101
+ if (pathname.startsWith('/__castle/'))
102
+ return null;
103
+ if (DOCUMENT_FETCH_DESTS.has(dest.toLowerCase()))
104
+ return null;
105
+ return { role: 'play', sandboxed: true };
106
+ }
107
+ /**
108
+ * origin/main's compatibilityContentRole, ported verbatim (b684425ac). For a
109
+ * compatibility-origin request without Fetch Metadata this IS the decision:
110
+ * see compatibilityContent.
111
+ */
112
+ function mainCompatibilityContentRole(req) {
113
+ if (process.env.CASTLE_ISOLATED_CONTENT_ORIGINS === '1')
114
+ return null;
115
+ const host = hostWithoutPort(req.headers.host || '');
116
+ if (!/^\d+-[a-z0-9]{14}\.sandboxes(?:-staging)?\.castle\.xyz$/.test(host)) {
117
+ return null;
118
+ }
119
+ let requestUrl;
120
+ try {
121
+ requestUrl = new URL(req.url || '/', requestOrigin(req));
122
+ }
123
+ catch {
124
+ return null;
125
+ }
126
+ // `/` and the IDE bundle belong to the trusted shell. Everything else is
127
+ // deck content in compatibility mode, where released mobile clients require
128
+ // both frames to stay on the castle.xyz shell origin.
129
+ if (requestUrl.pathname === '/' || requestUrl.pathname.startsWith('/__castle/ide/')) {
130
+ return null;
131
+ }
132
+ if (requestUrl.pathname === '/index.html') {
133
+ return requestUrl.searchParams.get('edit') === '0' ? 'play' : 'edit';
134
+ }
135
+ // Browser fetches made by a frame retain the document URL as their same-origin
136
+ // referrer. Use it to preserve the edit-only file-read boundary. Static deck
137
+ // assets do not need that capability and can safely use the play role fallback.
138
+ const referer = req.headers.referer;
139
+ if (typeof referer === 'string') {
140
+ try {
141
+ const referrerUrl = new URL(referer);
142
+ if (referrerUrl.origin === requestOrigin(req) && referrerUrl.pathname === '/index.html') {
143
+ return referrerUrl.searchParams.get('edit') === '0' ? 'play' : 'edit';
144
+ }
145
+ }
146
+ catch {
147
+ // Malformed referrers never receive edit privileges.
148
+ }
149
+ }
150
+ return requestUrl.pathname.startsWith('/__castle/') ? null : 'play';
151
+ }
152
+ /**
153
+ * A native app WebView, which is all a released Castle app opens the editor in:
154
+ * iOS/iPadOS WKWebView's default user agent has AppleWebKit but no `Safari/`
155
+ * token (every Safari, and every Chromium browser, carries one), and Android
156
+ * System WebView marks itself `; wv)`. Page script cannot change the user agent
157
+ * its browser sends, so deck code in a desktop or mobile browser can never
158
+ * look like this. Exported for the tests.
159
+ */
160
+ export function isNativeWebViewUserAgent(userAgent) {
161
+ if (!userAgent)
162
+ return false;
163
+ if (/; wv\)/.test(userAgent))
164
+ return true;
165
+ return /AppleWebKit\//.test(userAgent) && !/Safari\//.test(userAgent);
166
+ }
167
+ /** castle-www (castle.xyz and its subdomains), never a sandbox page. */
168
+ function isCastleWebReferrer(referer) {
169
+ try {
170
+ const url = new URL(referer);
171
+ const host = url.hostname.toLowerCase();
172
+ return (url.protocol === 'https:' &&
173
+ (host === 'castle.xyz' || host.endsWith('.castle.xyz')) &&
174
+ !/(?:^|\.)sandboxes(?:-staging)?\.castle\.xyz$/.test(host));
175
+ }
176
+ catch {
177
+ return false;
178
+ }
179
+ }
12
180
  // A signature covers the request path and nothing else, so every path it can
13
181
  // open must be a static file the path alone names. A query-driven endpoint
14
182
  // here (`/__castle/files/read?path=`) would be opened wholesale by one signature.
@@ -79,9 +247,27 @@ export class ServeSecurity {
79
247
  serveToken = randomBytes(32).toString('base64url');
80
248
  contentProxyToken = randomBytes(32).toString('base64url');
81
249
  signingKey = process.env.CASTLE_AGENT_TOKEN || randomBytes(32).toString('base64url');
250
+ // The nonce in every content label this serve mints. Random per process
251
+ // until useProjectState derives it from the project's identity.
82
252
  serveNonce = base32Lower(randomBytes(8));
253
+ // Nonces this process minted under before adopting another serve's record
254
+ // (two serves of one project): their labels must keep verifying.
255
+ retiredNonces = new Set();
256
+ // The project this serve keeps its state in (useProjectState), its real
257
+ // path, and its id from the content-origin record.
258
+ projectDir = null;
259
+ projectRealpath = '';
260
+ projectId = '';
83
261
  contentGrantExpiresAtSeconds = 0;
84
262
  pathKey = randomBytes(32).toString('base64url');
263
+ compatContentKey = randomBytes(18).toString('base64url');
264
+ // Set by the first protocol-2 mobile shell. A protocol-2 app can navigate its
265
+ // top frame to any castle.xyz URL, so once one has opened this project, deck
266
+ // code inside it could reopen the editor without the protocol and land in
267
+ // compatibility mode; from then on this project never grants it. Persisted
268
+ // (see useProtocol2Marker) so a restarted serve, under a deck that is still
269
+ // running in that app, does not forget.
270
+ protocol2ShellSeen = false;
85
271
  tickets = new Map();
86
272
  localContentPorts;
87
273
  localContentHost = '127.0.0.1';
@@ -89,6 +275,140 @@ export class ServeSecurity {
89
275
  this.publicPort = publicPort;
90
276
  this.localContentPorts = localContentPorts ?? null;
91
277
  }
278
+ /**
279
+ * Keep this serve's state in `projectDir` (`.castle/runtime/`, see
280
+ * projectState.ts): the protocol-2 marker and the content-origin record.
281
+ *
282
+ * Content origins stay stable across serves of this project: the record
283
+ * holds a random project id and the current grant expiry, and the nonce in
284
+ * every label is derived from the signing key, that id and the project's
285
+ * real path. The nonce is in the grant MAC input (whose format Ghost also
286
+ * verifies, so it cannot grow a field), so a record copied into another
287
+ * project -- or another project later served on the same port -- yields a
288
+ * different nonce and never verifies this project's labels. A missing or
289
+ * malformed record is absent (the first mint writes a fresh one); deck code
290
+ * that rewrites it only moves its own project's origins.
291
+ *
292
+ * Files an earlier build kept directly in `.castle/` (which cloud checkpoint
293
+ * capture rejects) are migrated: the marker moves, a v1 record is dropped.
294
+ */
295
+ useProjectState(projectDir) {
296
+ this.projectDir = projectDir;
297
+ try {
298
+ this.projectRealpath = fs.realpathSync(projectDir);
299
+ }
300
+ catch {
301
+ this.projectRealpath = path.resolve(projectDir);
302
+ }
303
+ this.migrateLegacyState();
304
+ const record = this.readContentOriginRecord();
305
+ this.adoptProjectId(record?.projectId ?? base32Lower(randomBytes(16)));
306
+ if (record)
307
+ this.contentGrantExpiresAtSeconds = record.expiresAtSeconds;
308
+ if (this.protocol2MarkerPresent())
309
+ this.protocol2ShellSeen = true;
310
+ }
311
+ adoptProjectId(projectId) {
312
+ if (this.projectId && projectId !== this.projectId)
313
+ this.retiredNonces.add(this.serveNonce);
314
+ this.projectId = projectId;
315
+ this.serveNonce = base32Lower(createHmac('sha256', this.signingKey)
316
+ .update(`castle-content-nonce-v1\n${projectId}\n${this.projectRealpath}`)
317
+ .digest()
318
+ .subarray(0, 8));
319
+ }
320
+ /** The state file `name`, if its directory is safe (created on demand), else null. */
321
+ stateFile(name, create) {
322
+ if (!this.projectDir)
323
+ return 'missing';
324
+ const dir = projectStateDir(this.projectDir, PROJECT_STATE_SEGMENTS, create);
325
+ if (dir.status === 'ok')
326
+ return { file: path.join(dir.dir, name) };
327
+ if (dir.status === 'unsafe')
328
+ console.warn(`refusing project state: ${dir.reason}`);
329
+ return dir.status;
330
+ }
331
+ migrateLegacyState() {
332
+ if (!this.projectDir)
333
+ return;
334
+ const legacy = projectStateDir(this.projectDir, LEGACY_STATE_SEGMENTS, false);
335
+ if (legacy.status !== 'ok')
336
+ return;
337
+ const oldMarker = path.join(legacy.dir, PROTOCOL2_MARKER_FILE);
338
+ if (statePathPresent(oldMarker)) {
339
+ // Fail closed: the old marker is removed only once the new one exists,
340
+ // and protocol2MarkerPresent still honors it until then.
341
+ if (this.writeProtocol2Marker())
342
+ removeStateEntry(oldMarker);
343
+ }
344
+ const oldRecord = path.join(legacy.dir, CONTENT_ORIGIN_FILE);
345
+ if (statePathPresent(oldRecord) && !removeStateEntry(oldRecord)) {
346
+ console.warn(`could not remove the old content-origin record ${oldRecord}`);
347
+ }
348
+ }
349
+ /**
350
+ * Whether a protocol-2 app shell has opened this project, read from disk on
351
+ * every call: another serve of the same project may have written it since
352
+ * this one started. Anything at the marker path counts, and so does an
353
+ * unsafe state directory (fail closed).
354
+ */
355
+ protocol2MarkerPresent() {
356
+ if (!this.projectDir)
357
+ return false;
358
+ const legacy = projectStateDir(this.projectDir, LEGACY_STATE_SEGMENTS, false);
359
+ if (legacy.status === 'ok' && statePathPresent(path.join(legacy.dir, PROTOCOL2_MARKER_FILE))) {
360
+ return true;
361
+ }
362
+ const marker = this.stateFile(PROTOCOL2_MARKER_FILE, false);
363
+ if (marker === 'missing')
364
+ return false;
365
+ if (marker === 'unsafe')
366
+ return true;
367
+ return statePathPresent(marker.file);
368
+ }
369
+ writeProtocol2Marker() {
370
+ const marker = this.stateFile(PROTOCOL2_MARKER_FILE, true);
371
+ if (typeof marker === 'string')
372
+ return false;
373
+ try {
374
+ atomicWriteFileSync(marker.file, JSON.stringify({ version: 1, seenAt: new Date().toISOString() }) + '\n');
375
+ return true;
376
+ }
377
+ catch (error) {
378
+ console.warn(`could not record the protocol-2 shell in ${marker.file}: ${error instanceof Error ? error.message : String(error)}`);
379
+ return false;
380
+ }
381
+ }
382
+ readContentOriginRecord() {
383
+ const record = this.stateFile(CONTENT_ORIGIN_FILE, false);
384
+ return typeof record === 'string'
385
+ ? null
386
+ : parseContentOriginRecord(readSmallStateFile(record.file));
387
+ }
388
+ writeContentOriginRecord() {
389
+ const record = this.stateFile(CONTENT_ORIGIN_FILE, true);
390
+ if (typeof record === 'string')
391
+ return;
392
+ try {
393
+ atomicWriteFileSync(record.file, JSON.stringify({
394
+ version: 2,
395
+ projectId: this.projectId,
396
+ expiresAtSeconds: this.contentGrantExpiresAtSeconds,
397
+ }) + '\n');
398
+ }
399
+ catch (error) {
400
+ // This process keeps its origins; only a restart would change them.
401
+ console.warn(`could not record content origins in ${record.file}: ${error instanceof Error ? error.message : String(error)}`);
402
+ }
403
+ }
404
+ noteProtocol2Shell() {
405
+ if (this.protocol2ShellSeen)
406
+ return;
407
+ // This process refuses compatibility from now on even if the write fails;
408
+ // only a restart could forget.
409
+ this.protocol2ShellSeen = true;
410
+ this.writeProtocol2Marker();
411
+ }
92
412
  setLocalContentPorts(ports) {
93
413
  if (this.localContentPorts)
94
414
  throw new Error('local content ports are already configured');
@@ -206,7 +526,7 @@ export class ServeSecurity {
206
526
  }
207
527
  }
208
528
  shellBootstrap(req) {
209
- const { editOrigin, playOrigin } = this.contentOrigins(req);
529
+ const { editOrigin, playOrigin, contentParams, expiresAtSeconds } = this.contentOrigins(req);
210
530
  let hostOrigin = null;
211
531
  try {
212
532
  const referrer = typeof req.headers.referer === 'string' ? new URL(req.headers.referer) : null;
@@ -227,6 +547,8 @@ export class ServeSecurity {
227
547
  return `<script>(function(){
228
548
  window.__CASTLE_SERVE_TOKEN__=${JSON.stringify(this.serveToken)};
229
549
  window.__CASTLE_CONTENT_ORIGINS__=${JSON.stringify({ edit: editOrigin, play: playOrigin })};
550
+ window.__CASTLE_CONTENT_ORIGINS_EXPIRES_AT__=${JSON.stringify(expiresAtSeconds ?? null)};
551
+ window.__CASTLE_CONTENT_PARAMS__=${JSON.stringify(contentParams ?? {})};
230
552
  window.__CASTLE_HOST_ORIGIN__=${JSON.stringify(hostOrigin)};
231
553
  var nativeFetch=window.fetch.bind(window);
232
554
  var authReloadKey='castle:serve-auth-reload';
@@ -265,16 +587,20 @@ window.fetch=function(input,init){
265
587
  };
266
588
  })();</script>`;
267
589
  }
268
- contentOrigins(req) {
590
+ contentOrigins(req, options = {}) {
269
591
  const host = hostWithoutPort(req.headers.host || 'localhost');
270
592
  const cloud = host.match(/^\d+-([a-z0-9]{14})\.(sandboxes(?:-staging)?\.castle\.xyz)$/);
271
- // Released clients that predate protocol 2 reject the separate registrable
272
- // content domain at the native WebView layer. Missing and unknown protocol
273
- // values therefore stay on the compatibility origin forever; only an
274
- // explicit client capability (or the staging override) opts into isolation.
275
- if (cloud && !this.requestsIsolatedContentOrigins(req)) {
593
+ // Released mobile clients that predate protocol 2 reject the separate
594
+ // registrable content domain at the native WebView layer, so only they stay
595
+ // on the shell origin. Every other shell -- a desktop browser, or a mobile
596
+ // host that advertises protocol 2 -- gets isolated edit/play origins.
597
+ if (cloud && options.allowCompatibility !== false && this.admitCompatibilityShell(req)) {
276
598
  const origin = requestOrigin(req);
277
- return { editOrigin: origin, playOrigin: origin };
599
+ return {
600
+ editOrigin: origin,
601
+ playOrigin: origin,
602
+ contentParams: { [COMPAT_CONTENT_PARAM]: this.compatContentKey },
603
+ };
278
604
  }
279
605
  const sandboxId = cloud?.[1] || 'localdev000000';
280
606
  const contentHeader = req.headers['x-castle-content-domain'];
@@ -295,19 +621,52 @@ window.fetch=function(input,init){
295
621
  const label = this.mintContentLabel(role, sandboxId, expiresAtSeconds);
296
622
  return `https://${label}.${contentDomain}`;
297
623
  };
298
- return { editOrigin: originFor('edit'), playOrigin: originFor('play') };
624
+ return {
625
+ editOrigin: originFor('edit'),
626
+ playOrigin: originFor('play'),
627
+ ...(expiresAtSeconds ? { expiresAtSeconds } : {}),
628
+ };
629
+ }
630
+ /**
631
+ * What `GET /__castle/content-origins` returns to an open shell refreshing
632
+ * its grants. Never compatibility origins: the refresh request carries none
633
+ * of what admission needs (no `embed=mobile`, a sandbox referrer), and a
634
+ * compatibility shell has no expiry to refresh. Isolated origins are exactly
635
+ * what the shell route would give the same shell now.
636
+ */
637
+ refreshedContentOrigins(req) {
638
+ const origins = this.contentOrigins(req, { allowCompatibility: false });
639
+ return {
640
+ edit: origins.editOrigin,
641
+ play: origins.playOrigin,
642
+ expiresAtSeconds: origins.expiresAtSeconds ?? null,
643
+ };
299
644
  }
300
645
  contentGrantExpiry() {
301
646
  const nowSeconds = Math.floor(Date.now() / 1000);
302
647
  const latestExpiry = nowSeconds + MAX_GRANT_SECONDS - GRANT_CLOCK_SKEW_SECONDS;
303
- // Expiry is part of the hostname: reuse it so reopening the shell can reuse
304
- // the browser's module cache. Until open shells support automatic refresh,
305
- // keep at least 11 hours for every new shell (about an hour of cache reuse).
306
- // Already-open shells keep their old, still-valid grants until expiry.
648
+ // Expiry is part of the hostname: reuse it so reopening the shell (or a
649
+ // restarted serve, through the project's content-origin record) gets the
650
+ // same origins and can reuse the browser's module cache and storage. Open
651
+ // shells renew their own grants an hour before expiry (contentFrames.ts),
652
+ // so reuse runs until MIN_CONTENT_GRANT_REMAINING_SECONDS (renewal lead +
653
+ // margin) is left: about 10h45m of every 12h grant, and no grant handed
654
+ // out -- a renewal included -- is ever already due for renewal.
307
655
  // Also remint after a backwards clock jump rather than exceed Ghost's cap.
308
- if (this.contentGrantExpiresAtSeconds - nowSeconds < MIN_CONTENT_GRANT_REMAINING_SECONDS ||
309
- this.contentGrantExpiresAtSeconds > latestExpiry) {
310
- this.contentGrantExpiresAtSeconds = latestExpiry;
656
+ const usable = (expiry) => expiry - nowSeconds >= MIN_CONTENT_GRANT_REMAINING_SECONDS && expiry <= latestExpiry;
657
+ if (!usable(this.contentGrantExpiresAtSeconds)) {
658
+ // Another serve of this project may have recorded a newer grant since
659
+ // this one started: share it rather than overwrite it.
660
+ const record = this.projectDir ? this.readContentOriginRecord() : null;
661
+ if (record && record.projectId !== this.projectId)
662
+ this.adoptProjectId(record.projectId);
663
+ if (record && usable(record.expiresAtSeconds)) {
664
+ this.contentGrantExpiresAtSeconds = record.expiresAtSeconds;
665
+ }
666
+ else {
667
+ this.contentGrantExpiresAtSeconds = latestExpiry;
668
+ this.writeContentOriginRecord();
669
+ }
311
670
  }
312
671
  return this.contentGrantExpiresAtSeconds;
313
672
  }
@@ -371,15 +730,37 @@ window.fetch=function(input,init){
371
730
  if (publicPort !== this.publicPort ||
372
731
  expiresAtSeconds <= Math.floor(Date.now() / 1000) ||
373
732
  expiresAtSeconds > Math.floor(Date.now() / 1000) + MAX_GRANT_SECONDS ||
374
- match[5] !== this.serveNonce) {
733
+ (match[5] !== this.serveNonce && !this.retiredNonces.has(match[5]))) {
375
734
  return null;
376
735
  }
377
736
  const expected = this.contentMac(role, publicPort, match[3], expiresAtSeconds, match[5]);
378
737
  return safeEqual(expected, match[6]) ? role : null;
379
738
  }
380
739
  compatibilityContentRole(req) {
740
+ return this.compatibilityContent(req)?.role ?? null;
741
+ }
742
+ /**
743
+ * The content role a compatibility-mode request gets on the shell origin,
744
+ * and whether its response must be sandboxed (see CompatibilityContent).
745
+ */
746
+ compatibilityContent(req) {
381
747
  if (process.env.CASTLE_ISOLATED_CONTENT_ORIGINS === '1')
382
748
  return null;
749
+ // RULE: For any request on the compatibility (shared/shell) origin's
750
+ // deck-content path that carries no Sec-Fetch-Dest, the content-role
751
+ // decision and the response are exactly origin/main's behavior -- same
752
+ // role, same headers, same body, same fallbacks: no sandbox CSP, no
753
+ // extension blocks, no referrer heuristics. Clients without Fetch Metadata
754
+ // (pre-16.4 iOS WebViews, older WebKit) get main-level isolation; the
755
+ // stricter rules below apply only to requests that carry Sec-Fetch-Dest.
756
+ // (Isolated signed origins and loopback origins never reach here: the
757
+ // host check limits this to the compatibility shell host.)
758
+ const dest = req.headers['sec-fetch-dest'];
759
+ if (typeof dest !== 'string' || dest === '') {
760
+ const mainRole = mainCompatibilityContentRole(req);
761
+ return mainRole ? { role: mainRole, sandboxed: false } : null;
762
+ }
763
+ const role = (value) => ({ role: value, sandboxed: false });
383
764
  const host = hostWithoutPort(req.headers.host || '');
384
765
  if (!/^\d+-[a-z0-9]{14}\.sandboxes(?:-staging)?\.castle\.xyz$/.test(host)) {
385
766
  return null;
@@ -391,31 +772,66 @@ window.fetch=function(input,init){
391
772
  catch {
392
773
  return null;
393
774
  }
775
+ // Classify what Vite will serve, not the raw encoded path.
776
+ const pathname = servedPathname(requestUrl.pathname);
777
+ if (pathname === null)
778
+ return null;
394
779
  // `/` and the IDE bundle belong to the trusted shell. Everything else is
395
780
  // deck content in compatibility mode, where released mobile clients require
396
781
  // both frames to stay on the castle.xyz shell origin.
397
- if (requestUrl.pathname === '/' || requestUrl.pathname.startsWith('/__castle/ide/')) {
782
+ if (pathname === '/' || pathname.startsWith('/__castle/ide/')) {
398
783
  return null;
399
784
  }
400
- if (requestUrl.pathname === '/index.html') {
401
- return requestUrl.searchParams.get('edit') === '0' ? 'play' : 'edit';
785
+ if (pathname === '/index.html') {
786
+ // Only a frame URL minted by a compatibility-mode shell. Without the
787
+ // capability this is the shell route, which never serves deck HTML.
788
+ const capability = requestUrl.searchParams.get(COMPAT_CONTENT_PARAM) || '';
789
+ if (!capability || !safeEqual(capability, this.compatContentKey))
790
+ return null;
791
+ return role(requestUrl.searchParams.get('edit') === '0' ? 'play' : 'edit');
402
792
  }
403
- // Browser fetches made by a frame retain the document URL as their same-origin
404
- // referrer. Use it to preserve the edit-only file-read boundary. Static deck
405
- // assets do not need that capability and can safely use the play role fallback.
793
+ // Everything a compatibility frame loads carries a same-origin referrer:
794
+ // the frame document for its own requests, the importing module or the
795
+ // stylesheet for nested ones -- unless the deck suppressed it
796
+ // (`no-referrer`). A navigation from an isolated content origin carries a
797
+ // cross-origin referrer and gets no role below.
406
798
  const referer = req.headers.referer;
407
- if (typeof referer === 'string') {
408
- try {
409
- const referrerUrl = new URL(referer);
410
- if (referrerUrl.origin === requestOrigin(req) && referrerUrl.pathname === '/index.html') {
411
- return referrerUrl.searchParams.get('edit') === '0' ? 'play' : 'edit';
412
- }
413
- }
414
- catch {
415
- // Malformed referrers never receive edit privileges.
416
- }
799
+ if (referer === undefined)
800
+ return referrerlessStaticContent(dest, pathname);
801
+ if (typeof referer !== 'string')
802
+ return null;
803
+ let referrerUrl;
804
+ try {
805
+ referrerUrl = new URL(referer);
417
806
  }
418
- return requestUrl.pathname.startsWith('/__castle/') ? null : 'play';
807
+ catch {
808
+ return null;
809
+ }
810
+ if (referrerUrl.origin !== requestOrigin(req))
811
+ return null;
812
+ const referrerPath = servedPathname(referrerUrl.pathname);
813
+ if (referrerPath === null)
814
+ return null;
815
+ // The frame document's own requests keep the edit-only file-read boundary.
816
+ if (referrerPath === '/index.html') {
817
+ return role(referrerUrl.searchParams.get('edit') === '0' ? 'play' : 'edit');
818
+ }
819
+ // The shell document never loads deck content; only deck documents and
820
+ // modules may refer onward, and only to static deck paths.
821
+ if (referrerPath === '/' ||
822
+ referrerPath.startsWith('/__castle/') ||
823
+ pathname.startsWith('/__castle/')) {
824
+ return null;
825
+ }
826
+ // A referrer that is a static asset (a stylesheet, image, SVG, font,
827
+ // JSON...) is no deck document or module: it never unlocks a role of its
828
+ // own. An SVG served by the sandboxed fallback and rendered as a document
829
+ // could otherwise send its URL as the referrer of a navigation to a deck
830
+ // page. What such a referrer loads -- a stylesheet's fonts and images --
831
+ // gets exactly what a referrer-less load gets.
832
+ if (!mayReferOnward(referrerPath))
833
+ return referrerlessStaticContent(dest, pathname);
834
+ return role('play');
419
835
  }
420
836
  shellOrigin(req) {
421
837
  return requestOrigin(req);
@@ -429,16 +845,61 @@ window.fetch=function(input,init){
429
845
  serveNonce: this.serveNonce,
430
846
  }, this.signingKey);
431
847
  }
432
- requestsIsolatedContentOrigins(req) {
848
+ /**
849
+ * Whether this shell request gets compatibility origins (edit and play on the
850
+ * shell origin, the shell's own authority). Only a released mobile app may:
851
+ * castle-www forwards `embed=mobile` (every released app sends it) and, from
852
+ * protocol-2 apps, `mobileHostProtocol=2`. Those parameters are attacker
853
+ * controlled -- an isolated deck can navigate its frame or a new window to
854
+ * `?embed=mobile` -- so admission also needs what deck code cannot forge:
855
+ *
856
+ * - a native WebView user agent (a script cannot change its browser's UA,
857
+ * so no desktop or mobile browser is ever admitted);
858
+ * - castle-www as the embedder: a castle.xyz referrer and, where the browser
859
+ * sends Fetch Metadata, not a cross-site request (a navigation from the
860
+ * castlexyz.com content domain is cross-site and carries its referrer);
861
+ * - no protocol-2 shell ever seen on this project (see protocol2ShellSeen): inside
862
+ * a protocol-2 app, deck code can top-navigate to castle.xyz/admin/cloud
863
+ * with embed=mobile alone, and the request would otherwise look legitimate.
864
+ *
865
+ * See docs/mobile-webview-host-protocol.md for what remains.
866
+ */
867
+ admitCompatibilityShell(req) {
433
868
  if (process.env.CASTLE_ISOLATED_CONTENT_ORIGINS === '1')
434
- return true;
869
+ return false;
870
+ let params;
435
871
  try {
436
- return (new URL(req.url || '/', requestOrigin(req)).searchParams.get('mobileHostProtocol') ===
437
- MOBILE_HOST_PROTOCOL);
872
+ params = new URL(req.url || '/', requestOrigin(req)).searchParams;
438
873
  }
439
874
  catch {
440
875
  return false;
441
876
  }
877
+ if (params.get('embed') !== 'mobile')
878
+ return false;
879
+ const ua = req.headers['user-agent'];
880
+ const referer = req.headers.referer;
881
+ const fromAppWebView = isNativeWebViewUserAgent(typeof ua === 'string' ? ua : undefined) &&
882
+ req.headers['sec-fetch-site'] !== 'cross-site' &&
883
+ typeof referer === 'string' &&
884
+ isCastleWebReferrer(referer);
885
+ if (params.get('mobileHostProtocol') === MOBILE_HOST_PROTOCOL) {
886
+ // Never compatibility. Recorded only for what would otherwise be a real
887
+ // app shell, so a desktop browser (or deck code navigating one) with the
888
+ // flag cannot switch compatibility off for the project.
889
+ if (fromAppWebView)
890
+ this.noteProtocol2Shell();
891
+ return false;
892
+ }
893
+ if (this.protocol2ShellSeen)
894
+ return false;
895
+ if (!fromAppWebView)
896
+ return false;
897
+ // Another serve of this project may have recorded a protocol-2 shell.
898
+ if (this.protocol2MarkerPresent()) {
899
+ this.protocol2ShellSeen = true;
900
+ return false;
901
+ }
902
+ return true;
442
903
  }
443
904
  contentMac(role, publicPort, sandboxId, expiresAtSeconds, serveNonce) {
444
905
  return mintContentGrantLabel({ role, publicPort, sandboxId, expiresAtSeconds, serveNonce }, this.signingKey)