castle-web-cli 0.4.212 → 0.4.213

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.
Files changed (46) hide show
  1. package/dist/cover-bridge/play-cover-bridge.js +2 -0
  2. package/dist/externalSourcemaps.js +2 -1
  3. package/dist/ide.js +7 -2
  4. package/dist/playCover/bridge.d.ts +6 -0
  5. package/dist/playCover/bridge.js +159 -0
  6. package/dist/playCover/builtins.d.ts +29 -0
  7. package/dist/playCover/builtins.js +189 -0
  8. package/dist/playCover/capture.d.ts +53 -0
  9. package/dist/playCover/capture.js +419 -0
  10. package/dist/playCover/clone.d.ts +40 -0
  11. package/dist/playCover/clone.js +317 -0
  12. package/dist/playCover/engine.d.ts +37 -0
  13. package/dist/playCover/engine.js +76 -0
  14. package/dist/playCover/errors.d.ts +6 -0
  15. package/dist/playCover/errors.js +18 -0
  16. package/dist/playCover/images.d.ts +21 -0
  17. package/dist/playCover/images.js +180 -0
  18. package/dist/playCover/instrument.d.ts +49 -0
  19. package/dist/playCover/instrument.js +334 -0
  20. package/dist/playCover/protocol.d.ts +14 -0
  21. package/dist/playCover/protocol.js +139 -0
  22. package/dist/playCover/rasterize.d.ts +21 -0
  23. package/dist/playCover/rasterize.js +408 -0
  24. package/dist/playCover/resources.d.ts +31 -0
  25. package/dist/playCover/resources.js +823 -0
  26. package/dist/playCover/scratchCanvas.d.ts +4 -0
  27. package/dist/playCover/scratchCanvas.js +16 -0
  28. package/dist/playCover/textSamples.d.ts +36 -0
  29. package/dist/playCover/textSamples.js +412 -0
  30. package/dist/playCover/validate.d.ts +79 -0
  31. package/dist/playCover/validate.js +883 -0
  32. package/dist/playCover/verify.d.ts +56 -0
  33. package/dist/playCover/verify.js +578 -0
  34. package/dist/playCover/verifyRecord.d.ts +71 -0
  35. package/dist/playCover/verifyRecord.js +243 -0
  36. package/dist/playCoverGate.d.ts +4 -0
  37. package/dist/playCoverGate.js +57 -0
  38. package/dist/playCoverPlacement.d.ts +11 -0
  39. package/dist/playCoverPlacement.js +110 -0
  40. package/dist/serve.d.ts +1 -0
  41. package/dist/serve.js +35 -17
  42. package/dist/shell/assets/index-BPhS3Ysy.css +1 -0
  43. package/dist/shell/assets/{index-DzLbNBc7.js → index-CcJiCq02.js} +94 -92
  44. package/dist/shell/index.html +2 -2
  45. package/package.json +2 -2
  46. package/dist/shell/assets/index-BCrgYh76.css +0 -1
@@ -0,0 +1,823 @@
1
+ // Embeds the images and fonts a Play cover needs as data: URLs, before the
2
+ // frame is frozen, so the copy made at the capture boundary needs nothing from
3
+ // the network and the rasterized image cannot reach out for anything either.
4
+ //
5
+ // Adapted from the visual-snapshot prototype's serializer (see instrument.ts
6
+ // for provenance), with the same limits: no credentials, no referrer, redirects
7
+ // revalidated, a per-resource, total and count budget, static PNG/JPEG images
8
+ // and known font types only, and undiscoverable custom fonts rejected (a
9
+ // stylesheet font's local() sources are kept: the copy is drawn in this same
10
+ // browser, which resolves them as the page did). The one policy difference is the prototype's own "actual Play"
11
+ // rule: a cross-origin http(s) resource the rendered card already uses may be
12
+ // embedded when the browser can read it under CORS (no allowlist to configure
13
+ // per deck); an opaque one still rejects.
14
+ import { CoverCaptureError, fail } from './errors.js';
15
+ import { nativeFetch, trim } from './builtins.js';
16
+ import { checkImageBytes, pageTiedImage, recordNames, refuseBlockedImage, refuseUnloadedCssImage, refuseUnloadedImg, } from './images.js';
17
+ import { blockedFontUrls, trackedFontFaces } from './instrument.js';
18
+ import { decodePseudoContent, elementHasRenderedText, clearSheetCopies, familyNames, listMarkerText, refuseAncestorEffects, refuseViewportFixed, setSheetCopy, refuseHighlights, refuseStyledFirstLines, parseUrlFunctions, replaceUrlTokens, splitCssList, urlTokens, unquoteFamily, validateElement, visibleSnapshotElements, } from './validate.js';
19
+ const MAX_RESOURCE_BYTES = 4 * 1024 * 1024;
20
+ const MAX_TOTAL_RESOURCE_BYTES = 10 * 1024 * 1024;
21
+ const MAX_RESOURCES = 96;
22
+ const SAFE_IMAGE_DATA_URL = /^data:image\/(?:png|jpeg);base64,[a-z0-9+/=]+$/i;
23
+ const SAFE_FONT_DATA_URL = /^data:(?:font\/(?:woff2?|ttf|otf)|application\/(?:font-woff|font-sfnt|octet-stream));base64,[a-z0-9+/=]+$/i;
24
+ const FONT_MIME_CANONICAL = {
25
+ 'font/woff2': 'font/woff2',
26
+ 'font/woff': 'font/woff',
27
+ 'font/ttf': 'font/ttf',
28
+ 'font/otf': 'font/otf',
29
+ 'font/sfnt': 'font/sfnt',
30
+ 'font/collection': 'font/collection',
31
+ 'application/font-woff2': 'font/woff2',
32
+ 'application/font-woff': 'font/woff',
33
+ 'application/x-font-woff': 'font/woff',
34
+ 'application/font-sfnt': 'font/sfnt',
35
+ 'application/x-font-ttf': 'font/ttf',
36
+ 'application/x-font-truetype': 'font/ttf',
37
+ 'application/x-font-opentype': 'font/otf',
38
+ 'application/vnd.ms-opentype': 'font/otf',
39
+ 'application/octet-stream': 'application/octet-stream',
40
+ };
41
+ const GENERIC_FONT_NAMES = new Set([
42
+ 'serif',
43
+ 'sans-serif',
44
+ 'monospace',
45
+ 'cursive',
46
+ 'fantasy',
47
+ 'system-ui',
48
+ 'ui-serif',
49
+ 'ui-sans-serif',
50
+ 'ui-monospace',
51
+ 'emoji',
52
+ 'math',
53
+ 'fangsong',
54
+ ]);
55
+ const FONT_DESCRIPTOR_NAMES = {
56
+ style: 'font-style',
57
+ weight: 'font-weight',
58
+ stretch: 'font-stretch',
59
+ display: 'font-display',
60
+ unicodeRange: 'unicode-range',
61
+ featureSettings: 'font-feature-settings',
62
+ variationSettings: 'font-variation-settings',
63
+ ascentOverride: 'ascent-override',
64
+ descentOverride: 'descent-override',
65
+ lineGapOverride: 'line-gap-override',
66
+ sizeAdjust: 'size-adjust',
67
+ };
68
+ export function newBudget(signal) {
69
+ return { total: 0, cache: new Map(), cssCache: new Map(), signal };
70
+ }
71
+ export function bytesToDataUrl(bytes, mimeType) {
72
+ let binary = '';
73
+ for (let offset = 0; offset < bytes.length; offset += 0x8000) {
74
+ binary += String.fromCharCode(...bytes.subarray(offset, offset + 0x8000));
75
+ }
76
+ return `data:${mimeType};base64,${btoa(binary)}`;
77
+ }
78
+ // Every data: URL that enters the copy's CSS is plain base64 of a known type.
79
+ const PLAIN_DATA_URL = /^data:[a-z0-9.+/-]+;base64,[a-z0-9+/=]+$/i;
80
+ function checkedDataUrl(dataUrl) {
81
+ if (!PLAIN_DATA_URL.test(dataUrl))
82
+ fail('UNSUPPORTED_RESOURCE', 'an embedded resource is not a plain data: URL');
83
+ return dataUrl;
84
+ }
85
+ /** Where a resource may come from; an inline one is already embedded. */
86
+ export function allowedResourceUrl(rawUrl, kind, baseUrl = document.baseURI) {
87
+ if (kind === 'image' && SAFE_IMAGE_DATA_URL.test(rawUrl))
88
+ return { inline: true, url: rawUrl };
89
+ if (kind === 'font' && SAFE_FONT_DATA_URL.test(rawUrl))
90
+ return { inline: true, url: rawUrl };
91
+ if (/^\s*#/.test(rawUrl)) {
92
+ fail('UNSUPPORTED_RESOURCE_REFERENCE', `${kind} uses a document fragment reference`);
93
+ }
94
+ let url;
95
+ try {
96
+ url = new URL(rawUrl, baseUrl);
97
+ }
98
+ catch {
99
+ fail('INVALID_RESOURCE_URL', `cannot resolve ${kind} URL`);
100
+ }
101
+ if (!['http:', 'https:'].includes(url.protocol)) {
102
+ fail('UNSUPPORTED_RESOURCE_SCHEME', `${kind} uses ${url.protocol}`);
103
+ }
104
+ url.hash = '';
105
+ return { inline: false, url: url.href };
106
+ }
107
+ function resourceCount(budget) {
108
+ return budget.cache.size + budget.cssCache.size;
109
+ }
110
+ // Counts one more chunk of a resource against both caps, failing as soon as
111
+ // either is crossed.
112
+ function accountBytes(resourceBytes, chunkBytes, url, budget) {
113
+ if (resourceBytes > MAX_RESOURCE_BYTES)
114
+ fail('RESOURCE_TOO_LARGE', `${url}: more than ${MAX_RESOURCE_BYTES} bytes`);
115
+ budget.total += chunkBytes;
116
+ if (budget.total > MAX_TOTAL_RESOURCE_BYTES) {
117
+ fail('RESOURCE_BUDGET_EXCEEDED', `${budget.total} bytes exceeds ${MAX_TOTAL_RESOURCE_BYTES}`);
118
+ }
119
+ }
120
+ function accountResourceBytes(byteLength, url, budget) {
121
+ accountBytes(byteLength, byteLength, url, budget);
122
+ }
123
+ function concatChunks(chunks, length) {
124
+ const bytes = new Uint8Array(length);
125
+ let offset = 0;
126
+ for (const chunk of chunks) {
127
+ bytes.set(chunk, offset);
128
+ offset += chunk.byteLength;
129
+ }
130
+ return bytes;
131
+ }
132
+ // Reads the body chunk by chunk and stops the download the moment it crosses a
133
+ // cap, rather than buffering whatever the server sends and checking after.
134
+ async function readCapped(response, url, budget, stop) {
135
+ if (!response.body) {
136
+ const bytes = new Uint8Array(await response.arrayBuffer());
137
+ accountResourceBytes(bytes.byteLength, url, budget);
138
+ return bytes;
139
+ }
140
+ const reader = response.body.getReader();
141
+ const chunks = [];
142
+ let length = 0;
143
+ try {
144
+ for (;;) {
145
+ const { done, value } = await reader.read();
146
+ if (done)
147
+ break;
148
+ length += value.byteLength;
149
+ accountBytes(length, value.byteLength, url, budget);
150
+ chunks.push(value);
151
+ }
152
+ }
153
+ catch (error) {
154
+ stop();
155
+ reader.cancel().catch(() => { });
156
+ if (budget.signal.aborted)
157
+ fail('CAPTURE_CANCELED', 'the capture was canceled');
158
+ throw error;
159
+ }
160
+ return concatChunks(chunks, length);
161
+ }
162
+ async function openResponse(url, budget, signal) {
163
+ try {
164
+ // Same-origin or CORS-readable only. An opaque response cannot be read and
165
+ // throws here, which is the rejection for a site that does not allow it.
166
+ // Cookies go only to the deck's own origin (the legacy content-on-shell-host
167
+ // mode authenticates by cookie); a cross-origin request carries none.
168
+ return await nativeFetch(url, {
169
+ credentials: 'same-origin',
170
+ redirect: 'follow',
171
+ referrerPolicy: 'no-referrer',
172
+ // The copy the page loaded, from the HTTP cache it filled: a second
173
+ // network request may return something else (images.ts checks).
174
+ cache: 'force-cache',
175
+ mode: 'cors',
176
+ signal,
177
+ });
178
+ }
179
+ catch (error) {
180
+ if (budget.signal.aborted)
181
+ fail('CAPTURE_CANCELED', 'the capture was canceled');
182
+ fail(new URL(url).origin === location.origin
183
+ ? 'RESOURCE_FETCH_FAILED'
184
+ : 'RESOURCE_ORIGIN_NOT_ALLOWED', `${url}: ${error instanceof Error ? error.message : String(error)}`);
185
+ }
186
+ }
187
+ async function fetchBytes(url, kind, budget) {
188
+ // Each download can be stopped on its own (a cap crossed) or with the whole
189
+ // capture (cancel, deadline).
190
+ const controller = new AbortController();
191
+ const stop = () => controller.abort();
192
+ // A listener added to an already-aborted signal never fires, so a download
193
+ // queued behind a sibling's failure or a cancel must not start at all.
194
+ if (budget.signal.aborted)
195
+ fail('CAPTURE_CANCELED', `${url}: capture already stopped`);
196
+ budget.signal.addEventListener('abort', stop);
197
+ try {
198
+ const response = await openResponse(url, budget, controller.signal);
199
+ if (!response.ok) {
200
+ stop();
201
+ fail('RESOURCE_FETCH_FAILED', `${url}: HTTP ${response.status}`);
202
+ }
203
+ try {
204
+ allowedResourceUrl(response.url, kind);
205
+ }
206
+ catch (error) {
207
+ stop();
208
+ throw error;
209
+ }
210
+ const declared = Number(response.headers.get('content-length'));
211
+ if (Number.isFinite(declared) && declared > MAX_RESOURCE_BYTES) {
212
+ stop();
213
+ fail('RESOURCE_TOO_LARGE', `${url}: declared ${declared} bytes`);
214
+ }
215
+ const bytes = await readCapped(response, url, budget, stop);
216
+ const mime = trim((response.headers.get('content-type') ?? '').split(';')[0]).toLowerCase();
217
+ return { bytes, mime, finalUrl: response.url, uncacheable: uncacheable(response.headers) };
218
+ }
219
+ finally {
220
+ budget.signal.removeEventListener('abort', stop);
221
+ }
222
+ }
223
+ // A response a second request need not reproduce: no-store, or no-cache /
224
+ // max-age=0 with no validator (ETag, Last-Modified) to revalidate against.
225
+ // (Dev servers send no-cache with an ETag: that revalidates to the same bytes.)
226
+ function uncacheable(headers) {
227
+ const control = headers.get('cache-control') ?? '';
228
+ if (/\bno-store\b/i.test(control))
229
+ return true;
230
+ const mustRevalidate = /\b(?:no-cache|max-age\s*=\s*0)\b/i.test(control);
231
+ return mustRevalidate && !headers.get('etag') && !headers.get('last-modified');
232
+ }
233
+ function checkedMime(mime, kind, url) {
234
+ if (kind === 'image' && !['image/png', 'image/jpeg'].includes(mime)) {
235
+ fail('RESOURCE_TYPE_MISMATCH', `${url}: expected static PNG/JPEG, got ${mime || 'unknown'}`);
236
+ }
237
+ if (kind === 'font') {
238
+ // Exact types only, mapped to one spelling: the type ends up inside the
239
+ // copy's CSS, so a crafted Content-Type must never pass as a prefix match.
240
+ const canonical = mime ? FONT_MIME_CANONICAL[mime] : 'application/octet-stream';
241
+ if (!canonical)
242
+ fail('UNSUPPORTED_FONT', `${url}: expected a font type, got ${mime.slice(0, 60)}`);
243
+ return canonical;
244
+ }
245
+ return mime || 'image/png';
246
+ }
247
+ // An inline data: image gets the same byte check as a fetched one.
248
+ function checkInlineImage(dataUrl) {
249
+ const comma = dataUrl.indexOf(',');
250
+ const mime = dataUrl.slice(5, dataUrl.indexOf(';')).toLowerCase();
251
+ let binary;
252
+ try {
253
+ binary = atob(dataUrl.slice(comma + 1));
254
+ }
255
+ catch {
256
+ return fail('RESOURCE_TYPE_MISMATCH', 'an inline image is not valid base64');
257
+ }
258
+ const bytes = new Uint8Array(binary.length);
259
+ for (let index = 0; index < binary.length; index++)
260
+ bytes[index] = binary.charCodeAt(index);
261
+ checkImageBytes(bytes, mime, 'an inline image');
262
+ }
263
+ async function fetchEmbeddedResource(rawUrl, budget, kind, baseUrl, pageImage = null) {
264
+ const allowed = allowedResourceUrl(rawUrl, kind, baseUrl);
265
+ if (allowed.inline) {
266
+ if (kind === 'image')
267
+ checkInlineImage(allowed.url);
268
+ return allowed.url;
269
+ }
270
+ const cached = budget.cache.get(allowed.url);
271
+ if (cached !== undefined)
272
+ return await cached;
273
+ if (resourceCount(budget) >= MAX_RESOURCES) {
274
+ fail('TOO_MANY_RESOURCES', `more than ${MAX_RESOURCES} resources`);
275
+ }
276
+ const pending = (async () => {
277
+ const fetched = await fetchBytes(allowed.url, kind, budget);
278
+ const mime = checkedMime(fetched.mime, kind, allowed.url);
279
+ if (kind === 'image')
280
+ checkImageBytes(fetched.bytes, mime, allowed.url);
281
+ const dataUrl = bytesToDataUrl(fetched.bytes, mime);
282
+ if (kind !== 'image')
283
+ return dataUrl;
284
+ const embedded = await pageTiedImage(allowed.url, {
285
+ bytes: fetched.bytes,
286
+ mime,
287
+ dataUrl,
288
+ uncacheable: fetched.uncacheable,
289
+ }, pageImage);
290
+ if (embedded !== dataUrl)
291
+ accountResourceBytes(embedded.length, allowed.url, budget);
292
+ return embedded;
293
+ })();
294
+ budget.cache.set(allowed.url, pending);
295
+ try {
296
+ const result = await pending;
297
+ budget.cache.set(allowed.url, result);
298
+ return result;
299
+ }
300
+ catch (error) {
301
+ budget.cache.delete(allowed.url);
302
+ throw error;
303
+ }
304
+ }
305
+ async function rewriteResourceValue(value, budget, kind, baseUrl) {
306
+ // Only the url() tokens themselves are rewritten, by position: the same
307
+ // text inside a string (a local() name) stays as it was.
308
+ const replacements = [];
309
+ for (const token of urlTokens(value)) {
310
+ const embedded = checkedDataUrl(await fetchEmbeddedResource(token.url, budget, kind, baseUrl));
311
+ replacements.push([token, `url("${embedded}")`]);
312
+ }
313
+ return replaceUrlTokens(value, replacements);
314
+ }
315
+ /** The preloaded data: URL for a CSS value, synchronously, at the capture boundary. */
316
+ export function rewriteCssValueSynchronously(value, budget, label, property) {
317
+ const replacements = [];
318
+ for (const token of urlTokens(value)) {
319
+ const allowed = allowedResourceUrl(token.url, 'image');
320
+ if (allowed.inline)
321
+ continue;
322
+ const embedded = budget.cache.get(allowed.url);
323
+ if (typeof embedded !== 'string')
324
+ fail('RESOURCE_NOT_PRELOADED', `${label} ${property} was not preloaded`);
325
+ replacements.push([token, `url("${checkedDataUrl(embedded)}")`]);
326
+ }
327
+ return replaceUrlTokens(value, replacements);
328
+ }
329
+ const CAPTURE_ENDING = new Set([
330
+ 'CAPTURE_CANCELED',
331
+ 'RESOURCE_BUDGET_EXCEEDED',
332
+ 'TOO_MANY_RESOURCES',
333
+ 'RESOURCE_TOO_LARGE',
334
+ ]);
335
+ // A line clamp's declared display is read from the page's style rules
336
+ // (validate.ts lineClampDisplay); sheets the page cannot read are fetched
337
+ // under CORS first -- only when the card has a clamp to decide.
338
+ async function copyUnreadableSheetsForClamps(root, budget) {
339
+ clearSheetCopies();
340
+ const clamped = visibleSnapshotElements(root).some((element) => getComputedStyle(element).getPropertyValue('-webkit-line-clamp') !== 'none');
341
+ if (!clamped)
342
+ return;
343
+ for (const sheet of document.styleSheets) {
344
+ if (!sheet.href)
345
+ continue;
346
+ try {
347
+ void sheet.cssRules;
348
+ }
349
+ catch {
350
+ try {
351
+ const fetched = await fetchStylesheet(sheet.href, budget);
352
+ setSheetCopy(sheet.href, fetched.text);
353
+ }
354
+ catch (error) {
355
+ // A cancel or a spent budget ends the capture; anything else leaves
356
+ // the sheet unreadable, and a clamp that needs it refuses.
357
+ if (error instanceof CoverCaptureError && CAPTURE_ENDING.has(error.code))
358
+ throw error;
359
+ }
360
+ }
361
+ }
362
+ }
363
+ async function fetchStylesheet(rawUrl, budget) {
364
+ const allowed = allowedResourceUrl(rawUrl, 'stylesheet');
365
+ const cached = budget.cssCache.get(allowed.url);
366
+ if (cached)
367
+ return await cached;
368
+ if (resourceCount(budget) >= MAX_RESOURCES) {
369
+ fail('TOO_MANY_RESOURCES', `more than ${MAX_RESOURCES} resources`);
370
+ }
371
+ const pending = (async () => {
372
+ const fetched = await fetchBytes(allowed.url, 'stylesheet', budget);
373
+ if (fetched.mime !== 'text/css') {
374
+ fail('RESOURCE_TYPE_MISMATCH', `${allowed.url}: expected text/css, got ${fetched.mime || 'unknown'}`);
375
+ }
376
+ const text = new TextDecoder('utf-8', { fatal: true }).decode(fetched.bytes);
377
+ if (/@import\b/i.test(text))
378
+ fail('UNSUPPORTED_FONT_STYLESHEET', `${allowed.url}: @import is not supported`);
379
+ return { text, baseUrl: fetched.finalUrl };
380
+ })();
381
+ budget.cssCache.set(allowed.url, pending);
382
+ try {
383
+ return await pending;
384
+ }
385
+ catch (error) {
386
+ budget.cssCache.delete(allowed.url);
387
+ throw error;
388
+ }
389
+ }
390
+ function collectSnapshotInputs(root) {
391
+ const inputs = { imageSources: [], cssResources: [], usedTextFonts: new Set() };
392
+ // Forced colours repaint the page from system colours; the copy has none
393
+ // of that. Said plainly, before anything it would trip over.
394
+ if (matchMedia('(forced-colors: active)').matches) {
395
+ fail('UNSUPPORTED_FORCED_COLORS', 'the browser is in forced-colors mode');
396
+ }
397
+ refuseStyledFirstLines(root);
398
+ refuseHighlights(root);
399
+ refuseAncestorEffects(root);
400
+ let index = 0;
401
+ for (const element of visibleSnapshotElements(root)) {
402
+ const label = `${element.tagName.toLowerCase()}[${index++}]`;
403
+ validateElement(element, label);
404
+ if (element instanceof HTMLImageElement) {
405
+ const src = element.currentSrc || element.getAttribute('src') || '';
406
+ if (!src)
407
+ fail('UNSUPPORTED_RESOURCE', `${label} has no image source`);
408
+ refuseUnloadedImg(element, label);
409
+ refuseBlockedImage(src, label);
410
+ inputs.imageSources.push({ url: src, element });
411
+ }
412
+ collectStyleInputs(element, inputs);
413
+ }
414
+ // After each element's own checks, so a modal (fixed in the top layer)
415
+ // is refused as that, not as a fixed element.
416
+ refuseViewportFixed(root, visibleSnapshotElements(root));
417
+ return inputs;
418
+ }
419
+ function collectStyleInputs(element, inputs) {
420
+ for (const pseudo of [null, '::before', '::after']) {
421
+ const style = getComputedStyle(element, pseudo);
422
+ // A list item's marker is text too, drawn in the item's own font.
423
+ const rendersText = pseudo
424
+ ? decodePseudoContent(style.content) !== null && style.display !== 'none'
425
+ : elementHasRenderedText(element, style) || listMarkerText(element, style) !== null;
426
+ if (rendersText) {
427
+ for (const family of familyNames(style.fontFamily)) {
428
+ if (!GENERIC_FONT_NAMES.has(family))
429
+ inputs.usedTextFonts.add(family);
430
+ }
431
+ }
432
+ for (const property of style) {
433
+ // A custom property's url() is fetched only where a real property uses
434
+ // it, and that property carries the substituted value.
435
+ if (property.startsWith('--'))
436
+ continue;
437
+ const value = style.getPropertyValue(property);
438
+ // image-set() picks its candidate by the device's resolution; inside
439
+ // the SVG image it resolves at 1x, not the page's.
440
+ if (/image-set\(/i.test(value))
441
+ fail('UNSUPPORTED_IMAGE_SET', `${property} uses image-set()`);
442
+ const urls = parseUrlFunctions(value);
443
+ if (urls.length === 0)
444
+ continue;
445
+ for (const url of urls) {
446
+ refuseBlockedImage(url, property);
447
+ if (!allowedResourceUrl(url, 'image').inline)
448
+ refuseUnloadedCssImage(url, property);
449
+ }
450
+ inputs.cssResources.push(value);
451
+ }
452
+ }
453
+ }
454
+ function mediaApplies(media) {
455
+ return !media.mediaText || matchMedia(media.mediaText).matches;
456
+ }
457
+ // Every @font-face rule of a sheet in force, @import-ed sheets included.
458
+ function collectSheet(sheet, found) {
459
+ // A disabled sheet, or one whose media query is false here, adds no faces.
460
+ if (sheet.disabled || !mediaApplies(sheet.media))
461
+ return;
462
+ let list;
463
+ try {
464
+ list = sheet.cssRules;
465
+ }
466
+ catch {
467
+ if (!sheet.href)
468
+ fail('UNSUPPORTED_FONT_STYLESHEET', 'an inline stylesheet is not readable');
469
+ found.inaccessibleHrefs.push(sheet.href);
470
+ return;
471
+ }
472
+ collectFontFaceRules(list, found);
473
+ }
474
+ function collectFontFaceRules(list, found) {
475
+ for (const rule of list) {
476
+ if (rule instanceof CSSFontFaceRule)
477
+ found.rules.push(rule);
478
+ else if (rule instanceof CSSImportRule) {
479
+ if (rule.styleSheet && mediaApplies(rule.media))
480
+ collectSheet(rule.styleSheet, found);
481
+ }
482
+ else if (rule instanceof CSSMediaRule && !matchMedia(rule.media.mediaText).matches)
483
+ continue;
484
+ else if (rule instanceof CSSSupportsRule && !CSS.supports(rule.conditionText))
485
+ continue;
486
+ else if ('cssRules' in rule)
487
+ collectFontFaceRules(rule.cssRules, found);
488
+ }
489
+ }
490
+ // What a rule's url()s resolve against: its own stylesheet's URL, or for a
491
+ // sheet with none (an inline <style>, an imported sheet's parent chain up to
492
+ // one), the nearest ancestor sheet's, else the document's.
493
+ function ruleBaseUrl(rule) {
494
+ let sheet = rule.parentStyleSheet;
495
+ while (sheet) {
496
+ if (sheet.href)
497
+ return sheet.href;
498
+ // A constructed sheet's base URL is not exposed: unknown.
499
+ if (!sheet.ownerNode && !sheet.ownerRule)
500
+ return null;
501
+ sheet = sheet.ownerRule?.parentStyleSheet ?? null;
502
+ }
503
+ return document.baseURI;
504
+ }
505
+ // The document's sheets and its adopted (constructed) ones. Faces a shadow
506
+ // root declares are not searched: one the page loaded from there is simply
507
+ // uncovered, and refuses (embedFonts).
508
+ function documentFontFaceRules() {
509
+ const found = { rules: [], inaccessibleHrefs: [] };
510
+ for (const sheet of document.styleSheets)
511
+ collectSheet(sheet, found);
512
+ for (const sheet of document.adoptedStyleSheets ?? [])
513
+ collectSheet(sheet, found);
514
+ return found;
515
+ }
516
+ function parsedFontFaceRules(text, sourceUrl) {
517
+ const sheet = new CSSStyleSheet();
518
+ try {
519
+ sheet.replaceSync(text);
520
+ }
521
+ catch (error) {
522
+ fail('UNSUPPORTED_FONT_STYLESHEET', `${sourceUrl}: ${error instanceof Error ? error.message : ''}`);
523
+ }
524
+ const found = { rules: [], inaccessibleHrefs: [] };
525
+ collectFontFaceRules(sheet.cssRules, found);
526
+ return found.rules;
527
+ }
528
+ // The descriptors that pick a face, spelled the way the browser spells them:
529
+ // a throwaway FontFace normalizes the rule's text ("bold", "U+0000-00FF") the
530
+ // same way the page's own faces report theirs.
531
+ function faceKey(face) {
532
+ return [face.weight, face.style, face.stretch, face.unicodeRange].join('|').toLowerCase();
533
+ }
534
+ function ruleFaceKey(rule) {
535
+ const descriptors = {};
536
+ const read = (name) => trim(rule.style.getPropertyValue(name)) || undefined;
537
+ descriptors.weight = read('font-weight');
538
+ descriptors.style = read('font-style');
539
+ descriptors.stretch = read('font-stretch');
540
+ descriptors.unicodeRange = read('unicode-range');
541
+ try {
542
+ return faceKey(new FontFace('castle-cover-probe', 'url(data:,)', descriptors));
543
+ }
544
+ catch {
545
+ return fail('UNSUPPORTED_FONT_DESCRIPTOR', 'an @font-face rule has descriptors the browser rejects');
546
+ }
547
+ }
548
+ // Whether the page drew with this rule: every face of the same family and
549
+ // descriptors has loaded. A rule the page could not use -- its font blocked by
550
+ // font-src, or its face never needed -- is left out, so the copy falls back
551
+ // where the page does. Some loaded and some not means the faces cannot be told
552
+ // apart from their rules, so the capture refuses rather than guess.
553
+ function ruleIsLoaded(rule, family) {
554
+ const key = ruleFaceKey(rule);
555
+ const statuses = new Set();
556
+ for (const face of document.fonts ?? []) {
557
+ if (unquoteFamily(face.family) === family && faceKey(face) === key)
558
+ statuses.add(face.status);
559
+ }
560
+ if (statuses.size === 1 && statuses.has('loaded'))
561
+ return true;
562
+ if (!statuses.has('loaded'))
563
+ return false;
564
+ return fail('UNSUPPORTED_FONT', `${family} has faces the page loaded and faces it did not, with the same descriptors`);
565
+ }
566
+ // With font-display optional (or fallback, past its swap window) a face can
567
+ // finish loading while the page keeps drawing the fallback, so "loaded" does
568
+ // not mean "drawn". There is no robust way to tell which the page shows, so a
569
+ // face used with either is refused, conservatively, rather than guessed at.
570
+ function refuseUncertainDisplay(family, display) {
571
+ const value = trim(display).toLowerCase();
572
+ if (value === 'optional' || value === 'fallback') {
573
+ fail('UNSUPPORTED_FONT_DISPLAY', `${family} has font-display: ${value}; the page may still show the fallback (refused conservatively)`);
574
+ }
575
+ }
576
+ function fontUrlBlocked(rawUrl, baseUrl) {
577
+ return recordNames(blockedFontUrls, rawUrl, baseUrl ?? document.baseURI);
578
+ }
579
+ // The src list the page actually tried: every entry whose URL its CSP
580
+ // refused is dropped, in order, so the cover falls through to the same next
581
+ // source (another URL, or a local() face) the page did.
582
+ function unblockedSources(src, baseUrl) {
583
+ const entries = splitCssList(src);
584
+ const kept = entries.filter((entry) => !urlTokens(entry).some((token) => fontUrlBlocked(token.url, baseUrl)));
585
+ if (kept.length === 0)
586
+ fail('UNSUPPORTED_FONT_SOURCE', 'every source of a loaded face was blocked by the page');
587
+ return kept.join(', ');
588
+ }
589
+ async function embedFontFaceRule(rule, base, fonts) {
590
+ const family = unquoteFamily(rule.style.getPropertyValue('font-family'));
591
+ if (!fonts.used.has(family) || !ruleIsLoaded(rule, family))
592
+ return;
593
+ // Every loaded rule is embedded, in order, even for a face already covered:
594
+ // with the same descriptors the later rule wins, in the page and the copy.
595
+ const key = `${family}|${ruleFaceKey(rule)}`;
596
+ refuseUncertainDisplay(family, rule.style.getPropertyValue('font-display'));
597
+ const src = rule.style.getPropertyValue('src');
598
+ // local() entries stay as the browser serialized them; only url() entries
599
+ // are embedded, and a rule with none has nothing the cover can carry.
600
+ const urls = parseUrlFunctions(src);
601
+ if (urls.length === 0)
602
+ fail('UNSUPPORTED_FONT_SOURCE', `${family} has no URL source`);
603
+ // A constructed sheet's relative URLs resolve against a base the page
604
+ // cannot read back; only absolute ones are certain.
605
+ const baseUrl = base ?? absoluteOnly(urls, family);
606
+ const embedded = await rewriteResourceValue(unblockedSources(src, baseUrl), fonts.budget, 'font', baseUrl);
607
+ fonts.css.push(rule.cssText.replace(src, () => embedded));
608
+ fonts.covered.add(key);
609
+ }
610
+ function absoluteOnly(urls, family) {
611
+ for (const url of urls) {
612
+ if (!URL.canParse(url) && !/^data:/i.test(url)) {
613
+ fail('UNSUPPORTED_FONT_SOURCE', `${family} is in a constructed sheet with a relative URL`);
614
+ }
615
+ }
616
+ return document.baseURI;
617
+ }
618
+ // Everything a tracked FontFace contributes to the copy's <style> is built
619
+ // here from checked parts, never from the deck's raw strings: a descriptor or
620
+ // source string can hold "}", and would otherwise write rules of its own.
621
+ function cssUrl(dataUrl) {
622
+ return `url("${checkedDataUrl(dataUrl)}")`;
623
+ }
624
+ /** A CSS string literal for any text: quotes, backslashes and line breaks escaped. */
625
+ export function cssString(value) {
626
+ return `"${value.replace(/[\\"\n\r\f]/g, (char) => `\\${char.charCodeAt(0).toString(16)} `)}"`;
627
+ }
628
+ // One entry of a deck-written FontFace source: `url(...)` with optional
629
+ // format() and tech() hints naming plain keywords or strings. Anything else
630
+ // (local(), unknown functions) refuses.
631
+ const HINT_NAME = /^(?:"[A-Za-z0-9-]+"|'[A-Za-z0-9-]+'|[A-Za-z0-9-]+)$/;
632
+ const HINT = /^(format|tech)\(([^()]*)\)\s*/i;
633
+ function dynamicSourceEntry(family, entry) {
634
+ const tokens = urlTokens(entry);
635
+ if (tokens.length !== 1 || tokens[0].start !== 0) {
636
+ fail('UNSUPPORTED_FONT_SOURCE', `dynamic font ${family} has a source entry that is not url(...)`);
637
+ }
638
+ let rest = trim(entry.slice(tokens[0].end));
639
+ let hints = '';
640
+ while (rest) {
641
+ const match = HINT.exec(rest);
642
+ const names = match ? match[2].split(',').map((name) => trim(name)) : [];
643
+ if (!match || names.length === 0 || !names.every((name) => HINT_NAME.test(name))) {
644
+ fail('UNSUPPORTED_FONT_SOURCE', `dynamic font ${family} has a source hint the cover cannot copy`);
645
+ }
646
+ hints += ` ${match[1].toLowerCase()}(${names.join(', ')})`;
647
+ rest = rest.slice(match[0].length);
648
+ }
649
+ return { url: tokens[0].url, hints };
650
+ }
651
+ async function trackedFontSource(tracked, budget) {
652
+ const source = tracked.source;
653
+ if (typeof source === 'string') {
654
+ // The deck's own text, never re-serialized by the browser: a comment or an
655
+ // escape could make it read differently here than the browser read it.
656
+ if (source.includes('/*') || source.includes('\\')) {
657
+ fail('UNSUPPORTED_FONT_SOURCE', `dynamic font ${tracked.family} has a comment or escape in its source`);
658
+ }
659
+ // Relative URLs resolve against the base the page had when the deck made
660
+ // the face, not whatever it is now.
661
+ const entries = splitCssList(source)
662
+ .map((entry) => dynamicSourceEntry(tracked.family, entry))
663
+ .filter((entry) => !fontUrlBlocked(entry.url, tracked.baseUrl));
664
+ if (entries.length === 0) {
665
+ fail('UNSUPPORTED_FONT_SOURCE', `dynamic font ${tracked.family} does not have an embeddable URL source`);
666
+ }
667
+ const embedded = await Promise.all(entries.map((entry) => fetchEmbeddedResource(entry.url, budget, 'font', tracked.baseUrl)));
668
+ // Each entry keeps its format()/tech() hints -- rebuilt from checked
669
+ // names -- so the browser skips in the cover the entries it skipped on
670
+ // the page.
671
+ return embedded.map((dataUrl, index) => `${cssUrl(dataUrl)}${entries[index].hints}`).join(', ');
672
+ }
673
+ if (source instanceof ArrayBuffer || ArrayBuffer.isView(source)) {
674
+ const bytes = source instanceof ArrayBuffer
675
+ ? new Uint8Array(source)
676
+ : new Uint8Array(source.buffer, source.byteOffset, source.byteLength);
677
+ accountResourceBytes(bytes.byteLength, `dynamic font ${tracked.family}`, budget);
678
+ return cssUrl(bytesToDataUrl(bytes, 'application/octet-stream'));
679
+ }
680
+ fail('UNSUPPORTED_FONT_SOURCE', `dynamic font ${tracked.family} has an unknown source`);
681
+ }
682
+ // A descriptor value the browser has normalized, and only the characters a
683
+ // font descriptor needs: no ; { } @ \ < > / and balanced quotes.
684
+ const SAFE_DESCRIPTOR = /^[A-Za-z0-9\s.,%+\-#"'()_?]*$/;
685
+ function checkedDescriptor(family, name, value) {
686
+ const text = typeof value === 'string' ? value : '';
687
+ const balanced = (text.split('"').length - 1) % 2 === 0 && (text.split("'").length - 1) % 2 === 0;
688
+ if (!text || !SAFE_DESCRIPTOR.test(text) || !balanced) {
689
+ fail('UNSUPPORTED_FONT_DESCRIPTOR', `dynamic font ${family} has an unusable ${name}`);
690
+ }
691
+ return text;
692
+ }
693
+ // Descriptors are read back from the FontFace itself -- the browser's own
694
+ // parse of what the deck passed -- for the names the deck passed.
695
+ function fontDescriptorCss(face, family, descriptors) {
696
+ return Object.keys(descriptors)
697
+ .map((name) => {
698
+ const cssName = FONT_DESCRIPTOR_NAMES[name];
699
+ if (!cssName)
700
+ fail('UNSUPPORTED_FONT_DESCRIPTOR', `dynamic font ${family} uses descriptor ${name}`);
701
+ return `${cssName}:${checkedDescriptor(family, name, face[name])}`;
702
+ })
703
+ .join(';');
704
+ }
705
+ async function embedTrackedFonts(fonts) {
706
+ if (!document.fonts)
707
+ return;
708
+ for (const face of document.fonts) {
709
+ const tracked = trackedFontFaces.get(face);
710
+ // A face the browser could not load (or never needed) is not drawn on the
711
+ // page either.
712
+ if (!tracked || face.status !== 'loaded')
713
+ continue;
714
+ const family = unquoteFamily(tracked.family);
715
+ if (!fonts.used.has(family))
716
+ continue;
717
+ refuseUncertainDisplay(family, face.display);
718
+ const source = await trackedFontSource(tracked, fonts.budget);
719
+ const descriptors = fontDescriptorCss(face, tracked.family, tracked.descriptors);
720
+ fonts.trackedCss.push(`@font-face{font-family:${cssString(tracked.family)};src:${source};${descriptors}}`);
721
+ fonts.covered.add(`${family}|${faceKey(face)}`);
722
+ }
723
+ }
724
+ async function embedFonts(used, budget) {
725
+ const fonts = { used, css: [], trackedCss: [], covered: new Set(), budget };
726
+ await embedTrackedFonts(fonts);
727
+ const discovered = documentFontFaceRules();
728
+ for (const rule of discovered.rules)
729
+ await embedFontFaceRule(rule, ruleBaseUrl(rule), fonts);
730
+ if (uncoveredFaces(fonts).length > 0) {
731
+ for (const href of new Set(discovered.inaccessibleHrefs)) {
732
+ const stylesheet = await fetchStylesheet(href, budget);
733
+ for (const rule of parsedFontFaceRules(stylesheet.text, stylesheet.baseUrl)) {
734
+ await embedFontFaceRule(rule, stylesheet.baseUrl, fonts);
735
+ }
736
+ }
737
+ }
738
+ // Coverage is per face: a regular face embedded does not stand in for a
739
+ // bold one the page also loaded (the copy would synthesize bold).
740
+ const missing = uncoveredFaces(fonts);
741
+ if (missing.length > 0) {
742
+ fail('UNSUPPORTED_FONT', `DOM text uses ${missing[0]}, whose embeddable source was not found`);
743
+ }
744
+ const coveredFamilies = new Set([...fonts.covered].map((key) => key.split('|')[0]));
745
+ const webFonts = webFontFamilies();
746
+ for (const family of used) {
747
+ if (coveredFamilies.has(family))
748
+ continue;
749
+ // A family the page never loads as a web font is a system font name in a
750
+ // stack (`SFMono-Regular, Consolas, monospace`, `Georgia, serif`): the page
751
+ // shows whichever of them this machine has, and so does the copy, which
752
+ // is rasterized in this same browser -- an SVG image resolves system fonts
753
+ // exactly as the page does. (The prototype rejected these because its
754
+ // packets were replayed on another host; ours never leave this browser.)
755
+ // A web font that could not be embedded still rejects: without it, the
756
+ // copy would silently fall back to a different face.
757
+ if (!webFonts.has(family))
758
+ continue;
759
+ fail('UNSUPPORTED_FONT', `DOM text uses ${family}, but its embeddable source was not discoverable`);
760
+ }
761
+ return { css: [...fonts.css, ...fonts.trackedCss].join('\n'), families: [...coveredFamilies] };
762
+ }
763
+ // Each loaded face of a family the card's text uses that nothing embedded yet.
764
+ function uncoveredFaces(fonts) {
765
+ const missing = [];
766
+ for (const face of document.fonts ?? []) {
767
+ if (face.status !== 'loaded')
768
+ continue;
769
+ const family = unquoteFamily(face.family);
770
+ const key = `${family}|${faceKey(face)}`;
771
+ if (fonts.used.has(family) && !fonts.covered.has(key))
772
+ missing.push(key);
773
+ }
774
+ return missing;
775
+ }
776
+ // Every family the document has a loaded FontFace for -- from @font-face
777
+ // rules in any stylesheet (opaque cross-origin ones included) or constructed
778
+ // in script. A face in error is not drawn on the page, and a family none of
779
+ // whose faces loaded was passed over for every character (the page's text
780
+ // would have loaded it otherwise, e.g. "Inter, Lobster" with Inter covering
781
+ // all): its text falls back there, as it will in the copy.
782
+ function webFontFamilies() {
783
+ const families = new Set();
784
+ if (document.fonts) {
785
+ for (const face of document.fonts)
786
+ if (face.status === 'loaded')
787
+ families.add(unquoteFamily(face.family));
788
+ }
789
+ return families;
790
+ }
791
+ /** Validates the card, then embeds every image and font it renders. */
792
+ export async function preloadResources(root, signal) {
793
+ // The first failure decides the capture, so every download still running is
794
+ // stopped with it rather than left to finish for nobody.
795
+ const local = new AbortController();
796
+ const forward = () => local.abort();
797
+ signal.addEventListener('abort', forward);
798
+ if (signal.aborted)
799
+ local.abort();
800
+ const budget = newBudget(local.signal);
801
+ try {
802
+ await copyUnreadableSheetsForClamps(root, budget);
803
+ const inputs = collectSnapshotInputs(root);
804
+ await Promise.all([
805
+ ...inputs.imageSources.map(({ url, element }) => fetchEmbeddedResource(url, budget, 'image', undefined, element)),
806
+ ...inputs.cssResources.map((value) => rewriteResourceValue(value, budget, 'image')),
807
+ ]);
808
+ // Fonts settle first: which faces loaded decides which rules are embedded.
809
+ await document.fonts?.ready;
810
+ if (document.fonts && document.fonts.status !== 'loaded') {
811
+ fail('FONTS_PENDING', 'document fonts are not loaded');
812
+ }
813
+ const fonts = await embedFonts(inputs.usedTextFonts, budget);
814
+ return { budget, fontCss: fonts.css, fontFamilies: fonts.families };
815
+ }
816
+ catch (error) {
817
+ local.abort();
818
+ throw error;
819
+ }
820
+ finally {
821
+ signal.removeEventListener('abort', forward);
822
+ }
823
+ }