castle-web-cli 0.4.211 → 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.
- package/dist/cover-bridge/play-cover-bridge.js +2 -0
- package/dist/externalSourcemaps.d.ts +29 -0
- package/dist/externalSourcemaps.js +163 -0
- package/dist/fontFaceImports.d.ts +7 -0
- package/dist/fontFaceImports.js +129 -0
- package/dist/ide.js +7 -2
- package/dist/playCover/bridge.d.ts +6 -0
- package/dist/playCover/bridge.js +159 -0
- package/dist/playCover/builtins.d.ts +29 -0
- package/dist/playCover/builtins.js +189 -0
- package/dist/playCover/capture.d.ts +53 -0
- package/dist/playCover/capture.js +419 -0
- package/dist/playCover/clone.d.ts +40 -0
- package/dist/playCover/clone.js +317 -0
- package/dist/playCover/engine.d.ts +37 -0
- package/dist/playCover/engine.js +76 -0
- package/dist/playCover/errors.d.ts +6 -0
- package/dist/playCover/errors.js +18 -0
- package/dist/playCover/images.d.ts +21 -0
- package/dist/playCover/images.js +180 -0
- package/dist/playCover/instrument.d.ts +49 -0
- package/dist/playCover/instrument.js +334 -0
- package/dist/playCover/protocol.d.ts +14 -0
- package/dist/playCover/protocol.js +139 -0
- package/dist/playCover/rasterize.d.ts +21 -0
- package/dist/playCover/rasterize.js +408 -0
- package/dist/playCover/resources.d.ts +31 -0
- package/dist/playCover/resources.js +823 -0
- package/dist/playCover/scratchCanvas.d.ts +4 -0
- package/dist/playCover/scratchCanvas.js +16 -0
- package/dist/playCover/textSamples.d.ts +36 -0
- package/dist/playCover/textSamples.js +412 -0
- package/dist/playCover/validate.d.ts +79 -0
- package/dist/playCover/validate.js +883 -0
- package/dist/playCover/verify.d.ts +56 -0
- package/dist/playCover/verify.js +578 -0
- package/dist/playCover/verifyRecord.d.ts +71 -0
- package/dist/playCover/verifyRecord.js +243 -0
- package/dist/playCoverGate.d.ts +4 -0
- package/dist/playCoverGate.js +57 -0
- package/dist/playCoverPlacement.d.ts +11 -0
- package/dist/playCoverPlacement.js +110 -0
- package/dist/serve.d.ts +1 -0
- package/dist/serve.js +42 -17
- package/dist/shell/assets/index-BPhS3Ysy.css +1 -0
- package/dist/shell/assets/{index-DzLbNBc7.js → index-CcJiCq02.js} +94 -92
- package/dist/shell/index.html +2 -2
- package/package.json +2 -2
- package/dist/shell/assets/index-BCrgYh76.css +0 -1
|
@@ -0,0 +1,317 @@
|
|
|
1
|
+
// The synchronous half of a Play cover capture: an inert copy of the card made
|
|
2
|
+
// in one JavaScript turn at the end of an animation frame -- structure, every
|
|
3
|
+
// computed style inlined, canvases replaced by <img>s of their pixels, images
|
|
4
|
+
// and fonts already embedded as data: URLs. No scripts, handlers, links or
|
|
5
|
+
// external URLs survive into it.
|
|
6
|
+
//
|
|
7
|
+
// Adapted from the visual-snapshot prototype's serializer (see instrument.ts
|
|
8
|
+
// for provenance).
|
|
9
|
+
import { fail } from './errors.js';
|
|
10
|
+
import { contexts, natives } from './instrument.js';
|
|
11
|
+
import { allowedResourceUrl, rewriteCssValueSynchronously, } from './resources.js';
|
|
12
|
+
import { decodePseudoContent, HTML_NAMESPACE, lineClampDisplay, SVG_NAMESPACE, validateElement, } from './validate.js';
|
|
13
|
+
import { collectEffectClips, collectEffects, collectTextSamples, collectWebKitRefusedEffects, recordBitmap, } from './verifyRecord.js';
|
|
14
|
+
const MAX_NODES = 3_000;
|
|
15
|
+
const MAX_PACKAGE_BYTES = 12 * 1024 * 1024;
|
|
16
|
+
const PACKET_VERSION = 2;
|
|
17
|
+
const DROPPED_ATTRIBUTES = ['href', 'action', 'formaction', 'srcset', 'poster'];
|
|
18
|
+
function copyComputedStyle(source, target, pseudo, label, state) {
|
|
19
|
+
const style = getComputedStyle(source, pseudo);
|
|
20
|
+
for (const property of style) {
|
|
21
|
+
// Custom properties are already substituted into every property that
|
|
22
|
+
// uses them; their raw text is arbitrary and draws nothing itself.
|
|
23
|
+
if (property.startsWith('--'))
|
|
24
|
+
continue;
|
|
25
|
+
target.style.setProperty(property, rewriteCssValueSynchronously(style.getPropertyValue(property), state.budget, label, property), style.getPropertyPriority(property));
|
|
26
|
+
}
|
|
27
|
+
// A line-clamped -webkit-box reports display flow-root: without its box
|
|
28
|
+
// model restored, the copy clamps without the ellipsis (lineClampDisplay).
|
|
29
|
+
const clampDisplay = pseudo ? null : lineClampDisplay(source, style);
|
|
30
|
+
if (clampDisplay) {
|
|
31
|
+
target.style.setProperty('display', clampDisplay);
|
|
32
|
+
target.style.setProperty('-webkit-box-orient', 'vertical');
|
|
33
|
+
}
|
|
34
|
+
target.style.setProperty('animation', 'none', 'important');
|
|
35
|
+
target.style.setProperty('transition', 'none', 'important');
|
|
36
|
+
target.style.setProperty('caret-color', 'transparent', 'important');
|
|
37
|
+
target.style.setProperty('overflow-anchor', 'none', 'important');
|
|
38
|
+
}
|
|
39
|
+
function appendPseudo(source, target, pseudo, label, state) {
|
|
40
|
+
const style = getComputedStyle(source, pseudo);
|
|
41
|
+
const text = decodePseudoContent(style.content);
|
|
42
|
+
if (text === null || style.display === 'none')
|
|
43
|
+
return;
|
|
44
|
+
const node = document.createElement('span');
|
|
45
|
+
node.setAttribute('data-cover-pseudo', pseudo.slice(2));
|
|
46
|
+
node.textContent = text;
|
|
47
|
+
copyComputedStyle(source, node, pseudo, `${label}${pseudo}`, state);
|
|
48
|
+
if (pseudo === '::before')
|
|
49
|
+
target.prepend(node);
|
|
50
|
+
else
|
|
51
|
+
target.append(node);
|
|
52
|
+
}
|
|
53
|
+
function embeddedImageSource(source, value, budget) {
|
|
54
|
+
const allowed = allowedResourceUrl(source.currentSrc || value, 'image');
|
|
55
|
+
const embedded = allowed.inline ? allowed.url : budget.cache.get(allowed.url);
|
|
56
|
+
if (typeof embedded !== 'string')
|
|
57
|
+
fail('RESOURCE_NOT_PRELOADED', '<img> source was not preloaded');
|
|
58
|
+
return embedded;
|
|
59
|
+
}
|
|
60
|
+
function copySafeAttributes(source, target, budget, record) {
|
|
61
|
+
for (const attribute of source.attributes) {
|
|
62
|
+
const name = attribute.name.toLowerCase();
|
|
63
|
+
if (name === 'style' || name === 'id' || name === 'class' || name.startsWith('on'))
|
|
64
|
+
continue;
|
|
65
|
+
// The capture marks its own elements in the copy; a deck's attributes of
|
|
66
|
+
// that shape must never reach it, or it could steer what gets checked.
|
|
67
|
+
if (name.startsWith('data-cover-')) {
|
|
68
|
+
record.strippedMarks++;
|
|
69
|
+
continue;
|
|
70
|
+
}
|
|
71
|
+
if (DROPPED_ATTRIBUTES.includes(name))
|
|
72
|
+
continue;
|
|
73
|
+
if (name === 'src') {
|
|
74
|
+
if (!(source instanceof HTMLImageElement)) {
|
|
75
|
+
fail('UNSUPPORTED_RESOURCE', `<${source.tagName.toLowerCase()}> has src`);
|
|
76
|
+
}
|
|
77
|
+
target.setAttribute('src', embeddedImageSource(source, attribute.value, budget));
|
|
78
|
+
continue;
|
|
79
|
+
}
|
|
80
|
+
target.setAttribute(attribute.name, attribute.value);
|
|
81
|
+
}
|
|
82
|
+
if (source instanceof HTMLInputElement && ['checkbox', 'radio'].includes(source.type)) {
|
|
83
|
+
target.checked = source.checked;
|
|
84
|
+
if (source.checked)
|
|
85
|
+
target.setAttribute('checked', '');
|
|
86
|
+
else
|
|
87
|
+
target.removeAttribute('checked');
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
function canvasDataUrl(source, label, state) {
|
|
91
|
+
const tracked = contexts.get(source);
|
|
92
|
+
if (!tracked) {
|
|
93
|
+
fail('CANVAS_CONTEXT_UNKNOWN', `${label} context was created before capture installation or never requested`);
|
|
94
|
+
}
|
|
95
|
+
if (tracked.kind === 'unsupported')
|
|
96
|
+
fail('UNSUPPORTED_CANVAS_CONTEXT', `${label} uses ${tracked.requestedType}`);
|
|
97
|
+
if (tracked.kind === 'webgl') {
|
|
98
|
+
const frame = state.webglFrames.get(source);
|
|
99
|
+
if (!frame)
|
|
100
|
+
fail('WEBGL_CAPTURE_REQUIRED', `${label} needs an end-of-render capture`);
|
|
101
|
+
const gl = tracked.context;
|
|
102
|
+
if (!frame.valid)
|
|
103
|
+
fail('WEBGL_CAPTURE_STALE', `${label} was not captured synchronously in this turn`);
|
|
104
|
+
if (frame.width !== gl.drawingBufferWidth || frame.height !== gl.drawingBufferHeight) {
|
|
105
|
+
fail('WEBGL_CAPTURE_STALE', `${label} was resized after capture`);
|
|
106
|
+
}
|
|
107
|
+
return frame.dataUrl;
|
|
108
|
+
}
|
|
109
|
+
try {
|
|
110
|
+
return source.toDataURL('image/png');
|
|
111
|
+
}
|
|
112
|
+
catch (error) {
|
|
113
|
+
fail('CANVAS_READBACK_FAILED', `${label}: ${error instanceof Error ? error.message : ''}`);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
function cloneCanvas(source, label, state) {
|
|
117
|
+
const image = document.createElement('img');
|
|
118
|
+
const dataUrl = canvasDataUrl(source, label, state);
|
|
119
|
+
image.src = dataUrl;
|
|
120
|
+
image.alt = '';
|
|
121
|
+
image.draggable = false;
|
|
122
|
+
copyComputedStyle(source, image, null, label, state);
|
|
123
|
+
recordBitmap(source, image, dataUrl, state.record);
|
|
124
|
+
state.record.clones.set(source, image);
|
|
125
|
+
return image;
|
|
126
|
+
}
|
|
127
|
+
function cloneChildren(source, label, state) {
|
|
128
|
+
const children = [];
|
|
129
|
+
let childIndex = 0;
|
|
130
|
+
for (const child of source.childNodes) {
|
|
131
|
+
if (child.nodeType === Node.TEXT_NODE) {
|
|
132
|
+
children.push(document.createTextNode(child.textContent ?? ''));
|
|
133
|
+
}
|
|
134
|
+
else if (child instanceof Element) {
|
|
135
|
+
childIndex++;
|
|
136
|
+
if (getComputedStyle(child).display === 'none')
|
|
137
|
+
continue;
|
|
138
|
+
children.push(cloneElement(child, `${label} > ${child.tagName.toLowerCase()}:nth-child(${childIndex})`, state));
|
|
139
|
+
}
|
|
140
|
+
else if (child.nodeType !== Node.COMMENT_NODE) {
|
|
141
|
+
fail('UNSUPPORTED_NODE', `${label} contains node type ${child.nodeType}`);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
return children;
|
|
145
|
+
}
|
|
146
|
+
// Whether the page gives this element's scrollbars room: classic scrollbars do,
|
|
147
|
+
// overlay scrollbars (macOS by default) and headless browsers' hidden ones do
|
|
148
|
+
// not. The copy then draws them, or not, to match.
|
|
149
|
+
function isScrollContainer(target) {
|
|
150
|
+
const scrolls = (value) => value === 'auto' || value === 'scroll';
|
|
151
|
+
return scrolls(target.style.overflowX) || scrolls(target.style.overflowY);
|
|
152
|
+
}
|
|
153
|
+
// Scrolling is baked into a clipped, translated wrapper: the copy has no
|
|
154
|
+
// scroll position of its own to restore, and draws no scrollbars (a box whose
|
|
155
|
+
// scrollbars the page gives room is refused, validate.ts). The wrapper is the
|
|
156
|
+
// content box's width, so text wraps as it does on the page, and it starts
|
|
157
|
+
// where the page's content does -- below the top padding, which scrolls with it.
|
|
158
|
+
function appendScrolled(source, target, children) {
|
|
159
|
+
if (isScrollContainer(target))
|
|
160
|
+
target.style.setProperty('scrollbar-width', 'none', 'important');
|
|
161
|
+
if (!source.scrollLeft && !source.scrollTop) {
|
|
162
|
+
target.append(...children);
|
|
163
|
+
return;
|
|
164
|
+
}
|
|
165
|
+
const style = getComputedStyle(source);
|
|
166
|
+
const px = (value) => Number.parseFloat(value) || 0;
|
|
167
|
+
const contentWidth = source.clientWidth - px(style.paddingLeft) - px(style.paddingRight);
|
|
168
|
+
const contentHeight = source.scrollHeight - px(style.paddingTop) - px(style.paddingBottom);
|
|
169
|
+
const scroller = document.createElement('div');
|
|
170
|
+
scroller.style.cssText = [
|
|
171
|
+
'position:relative',
|
|
172
|
+
`width:${Math.max(0, contentWidth)}px`,
|
|
173
|
+
`min-height:${Math.max(0, contentHeight)}px`,
|
|
174
|
+
`transform:translate(${-source.scrollLeft}px,${-source.scrollTop}px)`,
|
|
175
|
+
'transform-origin:top left',
|
|
176
|
+
].join(';');
|
|
177
|
+
scroller.append(...children);
|
|
178
|
+
target.style.setProperty('overflow', 'hidden', 'important');
|
|
179
|
+
target.append(scroller);
|
|
180
|
+
}
|
|
181
|
+
function cloneElement(source, label, state) {
|
|
182
|
+
if (++state.nodes > MAX_NODES)
|
|
183
|
+
fail('PACKAGE_TOO_COMPLEX', `more than ${MAX_NODES} elements`);
|
|
184
|
+
validateElement(source, label);
|
|
185
|
+
if (source instanceof HTMLCanvasElement)
|
|
186
|
+
return cloneCanvas(source, label, state);
|
|
187
|
+
const target = source.namespaceURI === SVG_NAMESPACE
|
|
188
|
+
? document.createElementNS(SVG_NAMESPACE, source.localName)
|
|
189
|
+
: // <body> as the root is copied as a plain block: every property is
|
|
190
|
+
// inlined from its computed style, and a nested <body> is not a thing
|
|
191
|
+
// the rasterizer's document should have to interpret.
|
|
192
|
+
document.createElement(source === document.body ? 'div' : source.tagName.toLowerCase());
|
|
193
|
+
state.record.clones.set(source, target);
|
|
194
|
+
copySafeAttributes(source, target, state.budget, state.record);
|
|
195
|
+
copyComputedStyle(source, target, null, label, state);
|
|
196
|
+
const src = target.getAttribute('src');
|
|
197
|
+
if (source instanceof HTMLImageElement && src)
|
|
198
|
+
recordBitmap(source, target, src, state.record);
|
|
199
|
+
const html = source.namespaceURI === HTML_NAMESPACE;
|
|
200
|
+
if (html)
|
|
201
|
+
appendPseudo(source, target, '::before', label, state);
|
|
202
|
+
appendScrolled(source, target, cloneChildren(source, label, state));
|
|
203
|
+
if (html)
|
|
204
|
+
appendPseudo(source, target, '::after', label, state);
|
|
205
|
+
return target;
|
|
206
|
+
}
|
|
207
|
+
function rootScale(source) {
|
|
208
|
+
const value = getComputedStyle(source).transform;
|
|
209
|
+
if (value === 'none')
|
|
210
|
+
return null;
|
|
211
|
+
let matrix;
|
|
212
|
+
try {
|
|
213
|
+
matrix = new DOMMatrixReadOnly(value);
|
|
214
|
+
}
|
|
215
|
+
catch {
|
|
216
|
+
fail('UNSUPPORTED_ROOT_TRANSFORM', `cannot parse root transform ${value}`);
|
|
217
|
+
}
|
|
218
|
+
const epsilon = 1e-8;
|
|
219
|
+
if (!matrix.is2D ||
|
|
220
|
+
Math.abs(matrix.b) > epsilon ||
|
|
221
|
+
Math.abs(matrix.c) > epsilon ||
|
|
222
|
+
matrix.a <= 0 ||
|
|
223
|
+
matrix.d <= 0) {
|
|
224
|
+
fail('UNSUPPORTED_ROOT_TRANSFORM', 'only positive axis-aligned root scale/translation is supported');
|
|
225
|
+
}
|
|
226
|
+
return { scaleX: matrix.a, scaleY: matrix.d };
|
|
227
|
+
}
|
|
228
|
+
// A positioned/translated root is normalized into a cropped wrapper at the
|
|
229
|
+
// origin, so the copy's box is exactly the card's on-screen box.
|
|
230
|
+
function wrapTransformedRoot(clone, rect, scale, marker) {
|
|
231
|
+
for (const [property, value] of [
|
|
232
|
+
['position', 'absolute'],
|
|
233
|
+
['inset', 'auto'],
|
|
234
|
+
['left', '0'],
|
|
235
|
+
['top', '0'],
|
|
236
|
+
['right', 'auto'],
|
|
237
|
+
['bottom', 'auto'],
|
|
238
|
+
['margin', '0'],
|
|
239
|
+
['transform-origin', 'top left'],
|
|
240
|
+
['transform', `scale(${scale.scaleX},${scale.scaleY})`],
|
|
241
|
+
]) {
|
|
242
|
+
clone.style.setProperty(property, value, 'important');
|
|
243
|
+
}
|
|
244
|
+
const wrapper = document.createElement('div');
|
|
245
|
+
wrapper.setAttribute(`${marker}-root-wrapper`, '');
|
|
246
|
+
wrapper.style.cssText = `position:relative;width:${rect.width}px;height:${rect.height}px;overflow:hidden`;
|
|
247
|
+
wrapper.append(clone);
|
|
248
|
+
return wrapper;
|
|
249
|
+
}
|
|
250
|
+
/** Copies `source` into an inert packet. Synchronous by contract. */
|
|
251
|
+
export function serializeCard(source, budget, fontCss, fontFamilies, webglFrames) {
|
|
252
|
+
const scale = rootScale(source);
|
|
253
|
+
const rect = source.getBoundingClientRect();
|
|
254
|
+
if (!(rect.width > 0 && rect.height > 0))
|
|
255
|
+
fail('EMPTY_TARGET', 'target has no visible bounds');
|
|
256
|
+
const record = {
|
|
257
|
+
originX: rect.left,
|
|
258
|
+
originY: rect.top,
|
|
259
|
+
scaleX: scale?.scaleX ?? 1,
|
|
260
|
+
scaleY: scale?.scaleY ?? 1,
|
|
261
|
+
root: source,
|
|
262
|
+
bitmaps: [],
|
|
263
|
+
unverified: 0,
|
|
264
|
+
clones: new Map(),
|
|
265
|
+
marker: newMarker(),
|
|
266
|
+
strippedMarks: 0,
|
|
267
|
+
};
|
|
268
|
+
let clone = cloneElement(source, source.tagName.toLowerCase(), {
|
|
269
|
+
nodes: 0,
|
|
270
|
+
budget,
|
|
271
|
+
webglFrames,
|
|
272
|
+
record,
|
|
273
|
+
});
|
|
274
|
+
// The card is positioned in the live page (centered, or offset by its
|
|
275
|
+
// parent); the copy starts at the origin of its own box.
|
|
276
|
+
if (scale)
|
|
277
|
+
clone = wrapTransformedRoot(clone, rect, scale, record.marker);
|
|
278
|
+
else
|
|
279
|
+
pinRootToOrigin(clone);
|
|
280
|
+
// Before the HTML is taken: it tags the clipping boxes in the copy.
|
|
281
|
+
const effectClips = collectEffectClips(source, record);
|
|
282
|
+
const html = clone.outerHTML;
|
|
283
|
+
const byteLength = new TextEncoder().encode(html + fontCss).byteLength;
|
|
284
|
+
if (byteLength > MAX_PACKAGE_BYTES)
|
|
285
|
+
fail('PACKAGE_TOO_LARGE', `${byteLength} bytes exceeds ${MAX_PACKAGE_BYTES}`);
|
|
286
|
+
return {
|
|
287
|
+
version: PACKET_VERSION,
|
|
288
|
+
width: Math.ceil(rect.width),
|
|
289
|
+
height: Math.ceil(rect.height),
|
|
290
|
+
backdropColor: getComputedStyle(document.body).backgroundColor,
|
|
291
|
+
html,
|
|
292
|
+
fontCss,
|
|
293
|
+
byteLength,
|
|
294
|
+
bitmaps: record.bitmaps,
|
|
295
|
+
unverifiedBitmaps: record.unverified,
|
|
296
|
+
textSamples: collectTextSamples(source, fontFamilies),
|
|
297
|
+
effects: collectEffects(source),
|
|
298
|
+
webkitEffects: collectWebKitRefusedEffects(source),
|
|
299
|
+
effectClips,
|
|
300
|
+
marker: record.marker,
|
|
301
|
+
strippedMarks: record.strippedMarks,
|
|
302
|
+
};
|
|
303
|
+
}
|
|
304
|
+
function newMarker() {
|
|
305
|
+
const bytes = new Uint8Array(6);
|
|
306
|
+
natives.getRandomValues(bytes);
|
|
307
|
+
return `data-cover-${Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('')}`;
|
|
308
|
+
}
|
|
309
|
+
function pinRootToOrigin(clone) {
|
|
310
|
+
const position = clone.style.getPropertyValue('position');
|
|
311
|
+
if (position === 'fixed' || position === 'absolute' || position === 'sticky') {
|
|
312
|
+
clone.style.setProperty('position', 'relative', 'important');
|
|
313
|
+
}
|
|
314
|
+
for (const side of ['left', 'top', 'right', 'bottom'])
|
|
315
|
+
clone.style.setProperty(side, 'auto', 'important');
|
|
316
|
+
clone.style.setProperty('margin', '0', 'important');
|
|
317
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
export interface EngineHints {
|
|
2
|
+
userAgent: string;
|
|
3
|
+
platform?: string;
|
|
4
|
+
maxTouchPoints?: number;
|
|
5
|
+
/** navigator.vendor: "Apple Computer, Inc." in WebKit, "Google Inc." in Chromium. */
|
|
6
|
+
vendor?: string;
|
|
7
|
+
}
|
|
8
|
+
export declare function isWebKitEngine(hints: EngineHints): boolean;
|
|
9
|
+
declare global {
|
|
10
|
+
interface Window {
|
|
11
|
+
/** Test seam: treat this page as WebKit (a deck can only refuse itself with it). */
|
|
12
|
+
__castleCoverAssumeWebKit?: boolean;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* v1 refuses every capture in WebKit, before anything is frozen or fetched:
|
|
17
|
+
* Safari kept finding ways to draw a wrong cover that no check made from its
|
|
18
|
+
* own drawing could see (the hard HUD shadow; data: images painted late). The
|
|
19
|
+
* WebKit code paths stay -- the effect rule, the unverifiable-bitmap rule, the
|
|
20
|
+
* check strip's data: sentinels -- for a diagnostic build to exercise, so
|
|
21
|
+
* Safari can be re-enabled with evidence.
|
|
22
|
+
*
|
|
23
|
+
* TODO(safari re-enable): before turning this off, the sentinel should use a
|
|
24
|
+
* fresh image per draw (a cached 2x2 can be painted while a card's own
|
|
25
|
+
* background images are not), and the redraw loop must not stop early on
|
|
26
|
+
* identical failures before the halfway re-decode has been tried, since
|
|
27
|
+
* WebKit's late paint can repeat identically.
|
|
28
|
+
*/
|
|
29
|
+
export declare function refuseWebKitCapture(): void;
|
|
30
|
+
/** Whether the current page should follow the WebKit rules. */
|
|
31
|
+
export declare function runningInWebKit(): boolean;
|
|
32
|
+
/**
|
|
33
|
+
* WebKit's rule, applied twice: here before anything is frozen, and again on
|
|
34
|
+
* the card as captured (rasterize.ts) -- an effect the deck adds in the very
|
|
35
|
+
* frame being captured (a hover, a pulse, a glow) must be refused too.
|
|
36
|
+
*/
|
|
37
|
+
export declare function refuseWebKitEffects(effects: string[]): void;
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
// Which rendering engine is drawing the cover. Used for one rule only: WebKit
|
|
2
|
+
// is refused any card with a shadow or blur (EFFECT_NOT_REPRODUCIBLE), because
|
|
3
|
+
// Safari 18.6 was seen to draw a translucent HUD's box-shadow as a hard,
|
|
4
|
+
// shifted rectangle that passed every check the capture could make -- the
|
|
5
|
+
// same wrong drawing whether clipped or not, and away from any edge. See
|
|
6
|
+
// .claude/skills/screenshots/SKILL.md for the evidence.
|
|
7
|
+
//
|
|
8
|
+
// Every browser on iOS and iPadOS is WebKit whatever it calls itself (Chrome
|
|
9
|
+
// there is CriOS, Firefox FxiOS, Edge EdgiOS), and so is the Castle app's
|
|
10
|
+
// WKWebView. Elsewhere, AppleWebKit without a Chromium token is Safari or
|
|
11
|
+
// another WebKit browser; Chromium browsers (Chrome, Edge, Opera, Samsung
|
|
12
|
+
// Internet, Android WebView) all carry "Chrome/" or "Chromium/", and Firefox
|
|
13
|
+
// carries no AppleWebKit at all.
|
|
14
|
+
import { fail } from './errors.js';
|
|
15
|
+
const IOS_DEVICE = /\((?:iPhone|iPad|iPod)[;)]/;
|
|
16
|
+
const IOS_BROWSER = /\b(?:CriOS|FxiOS|EdgiOS|OPiOS|GSA)\//;
|
|
17
|
+
const CHROMIUM = /\b(?:Chrome|Chromium|HeadlessChrome)\//;
|
|
18
|
+
export function isWebKitEngine(hints) {
|
|
19
|
+
const ua = hints.userAgent;
|
|
20
|
+
if (IOS_DEVICE.test(ua) || IOS_BROWSER.test(ua))
|
|
21
|
+
return true;
|
|
22
|
+
// iPadOS asks for desktop sites as a Mac; only an iPad has a touch screen.
|
|
23
|
+
if (hints.platform === 'MacIntel' && (hints.maxTouchPoints ?? 0) > 1)
|
|
24
|
+
return true;
|
|
25
|
+
if (CHROMIUM.test(ua))
|
|
26
|
+
return false;
|
|
27
|
+
// A WebKit browser whose user agent was changed or trimmed still reports
|
|
28
|
+
// Apple as its vendor.
|
|
29
|
+
return /AppleWebKit\//.test(ua) || hints.vendor === 'Apple Computer, Inc.';
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* v1 refuses every capture in WebKit, before anything is frozen or fetched:
|
|
33
|
+
* Safari kept finding ways to draw a wrong cover that no check made from its
|
|
34
|
+
* own drawing could see (the hard HUD shadow; data: images painted late). The
|
|
35
|
+
* WebKit code paths stay -- the effect rule, the unverifiable-bitmap rule, the
|
|
36
|
+
* check strip's data: sentinels -- for a diagnostic build to exercise, so
|
|
37
|
+
* Safari can be re-enabled with evidence.
|
|
38
|
+
*
|
|
39
|
+
* TODO(safari re-enable): before turning this off, the sentinel should use a
|
|
40
|
+
* fresh image per draw (a cached 2x2 can be painted while a card's own
|
|
41
|
+
* background images are not), and the redraw loop must not stop early on
|
|
42
|
+
* identical failures before the halfway re-decode has been tried, since
|
|
43
|
+
* WebKit's late paint can repeat identically.
|
|
44
|
+
*/
|
|
45
|
+
export function refuseWebKitCapture() {
|
|
46
|
+
const allowed = typeof __COVER_ALLOW_WEBKIT__ === 'boolean' && __COVER_ALLOW_WEBKIT__;
|
|
47
|
+
if (runningInWebKit() && !allowed)
|
|
48
|
+
fail('BROWSER_UNSUPPORTED', 'webkit: covers are not made in WebKit yet');
|
|
49
|
+
}
|
|
50
|
+
// Read once, when this module loads: in the deck frame that is the bridge's
|
|
51
|
+
// first line, before any deck code runs, so a deck that later redefines
|
|
52
|
+
// navigator.userAgent (to pass for Chrome inside Safari) changes nothing. The
|
|
53
|
+
// shell, which the deck cannot reach, makes the same check on its own page.
|
|
54
|
+
const LOADED_HINTS = typeof navigator === 'undefined'
|
|
55
|
+
? null
|
|
56
|
+
: {
|
|
57
|
+
userAgent: navigator.userAgent,
|
|
58
|
+
platform: navigator.platform,
|
|
59
|
+
maxTouchPoints: navigator.maxTouchPoints,
|
|
60
|
+
vendor: navigator.vendor,
|
|
61
|
+
};
|
|
62
|
+
/** Whether the current page should follow the WebKit rules. */
|
|
63
|
+
export function runningInWebKit() {
|
|
64
|
+
if (typeof window !== 'undefined' && window.__castleCoverAssumeWebKit === true)
|
|
65
|
+
return true;
|
|
66
|
+
return LOADED_HINTS !== null && isWebKitEngine(LOADED_HINTS);
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* WebKit's rule, applied twice: here before anything is frozen, and again on
|
|
70
|
+
* the card as captured (rasterize.ts) -- an effect the deck adds in the very
|
|
71
|
+
* frame being captured (a hover, a pulse, a glow) must be refused too.
|
|
72
|
+
*/
|
|
73
|
+
export function refuseWebKitEffects(effects) {
|
|
74
|
+
if (effects.length)
|
|
75
|
+
fail('EFFECT_NOT_REPRODUCIBLE', `webkit: the card uses ${effects.join(', ')}`);
|
|
76
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
// Every way a Play cover capture refuses is one of these, carrying a stable
|
|
2
|
+
// code (see protocol.ts for what a creator is told about each). The capture is
|
|
3
|
+
// fail-closed by design: an unsupported case rejects with its code rather than
|
|
4
|
+
// producing a less faithful picture.
|
|
5
|
+
export class CoverCaptureError extends Error {
|
|
6
|
+
code;
|
|
7
|
+
constructor(code, message) {
|
|
8
|
+
super(`${code}: ${message}`);
|
|
9
|
+
this.name = 'CoverCaptureError';
|
|
10
|
+
this.code = code;
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
export function fail(code, message) {
|
|
14
|
+
throw new CoverCaptureError(code, message);
|
|
15
|
+
}
|
|
16
|
+
export function errorCode(error) {
|
|
17
|
+
return error instanceof CoverCaptureError ? error.code : 'CAPTURE_FAILED';
|
|
18
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/** Whether a record of reported URLs (CSP, resource timing) names this one. */
|
|
2
|
+
export declare function recordNames(record: Record<string, true>, rawUrl: string, base: string): boolean;
|
|
3
|
+
export declare function refuseBlockedImage(url: string, label: string): void;
|
|
4
|
+
/** A CSS image URL the page has not finished loading refuses. */
|
|
5
|
+
export declare function refuseUnloadedCssImage(url: string, label: string): void;
|
|
6
|
+
/** An <img> that has not finished loading (or failed) refuses. */
|
|
7
|
+
export declare function refuseUnloadedImg(image: HTMLImageElement, label: string): void;
|
|
8
|
+
/**
|
|
9
|
+
* The data: URL to embed for a fetched image, tied to what the page shows.
|
|
10
|
+
* `pageImage` is the page's own <img> when there is one; for a CSS image a
|
|
11
|
+
* fresh Image of the same URL stands in for it.
|
|
12
|
+
*/
|
|
13
|
+
/** Only PNG and JPEG bytes, and no animated PNG (the page shows its frames, the cover one). */
|
|
14
|
+
export declare function checkImageBytes(bytes: Uint8Array, mime: string, url: string): void;
|
|
15
|
+
export declare function pageTiedImage(url: string, fetched: {
|
|
16
|
+
bytes: Uint8Array;
|
|
17
|
+
mime: string;
|
|
18
|
+
dataUrl: string;
|
|
19
|
+
/** The response may not be reused (no-store, no-cache, max-age=0). */
|
|
20
|
+
uncacheable: boolean;
|
|
21
|
+
}, pageImage: HTMLImageElement | null): Promise<string>;
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
// What an embedded image may contain: only pixels the page itself shows.
|
|
2
|
+
//
|
|
3
|
+
// A cover's images are fetched again at capture time, and a second request
|
|
4
|
+
// can return something else (a per-request image, one the page is still
|
|
5
|
+
// loading, one its CSP blocked, a cache entry another document rewrote). So
|
|
6
|
+
// each fetched image is tied back to the page's own pixels before it is used:
|
|
7
|
+
//
|
|
8
|
+
// - An <img> must have finished loading, and the page's decoded image must be
|
|
9
|
+
// readable (same origin, or loaded with crossorigin under CORS). Its pixels
|
|
10
|
+
// are compared with the fetched copy's; where they differ the page's own
|
|
11
|
+
// pixels are embedded.
|
|
12
|
+
// - A CSS image (a background, say) must have a finished resource-timing
|
|
13
|
+
// entry, and a fresh Image of the same URL must be readable (same origin)
|
|
14
|
+
// and decode to the fetched copy's pixels.
|
|
15
|
+
// - An image whose pixels the page cannot read refuses (IMAGE_NOT_READABLE):
|
|
16
|
+
// workers, frames and other documents can rewrite the shared HTTP cache
|
|
17
|
+
// without a trace in this page, so nothing short of the pixels themselves
|
|
18
|
+
// ties a copy to what the page drew.
|
|
19
|
+
// - A URL the page's CSP img-src refused is never embedded.
|
|
20
|
+
import { parseReportedUrl } from './builtins.js';
|
|
21
|
+
import { fail } from './errors.js';
|
|
22
|
+
import { blockedImageUrls, loadedResources } from './instrument.js';
|
|
23
|
+
import { scratchCanvas } from './scratchCanvas.js';
|
|
24
|
+
import { releaseCanvas } from './verify.js';
|
|
25
|
+
// Past this many pixels an image is not decoded again for the comparison.
|
|
26
|
+
const MAX_COMPARED_PIXELS = 4096 * 4096;
|
|
27
|
+
/** Whether a record of reported URLs (CSP, resource timing) names this one. */
|
|
28
|
+
export function recordNames(record, rawUrl, base) {
|
|
29
|
+
const url = parseReportedUrl(rawUrl, base);
|
|
30
|
+
if (!url)
|
|
31
|
+
return false;
|
|
32
|
+
// A report names the URL without its fragment or credentials, or only its
|
|
33
|
+
// origin when it must not reveal more, or only its scheme ("data", "blob")
|
|
34
|
+
// for a URL with no origin to name.
|
|
35
|
+
return (record[url.reported] === true ||
|
|
36
|
+
record[url.origin] === true ||
|
|
37
|
+
record[url.protocol.slice(0, -1)] === true);
|
|
38
|
+
}
|
|
39
|
+
export function refuseBlockedImage(url, label) {
|
|
40
|
+
if (recordNames(blockedImageUrls, url, document.baseURI)) {
|
|
41
|
+
fail('RESOURCE_BLOCKED_BY_PAGE', `${label}: the page's CSP img-src blocked ${url}`);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
/** A CSS image URL the page has not finished loading refuses. */
|
|
45
|
+
export function refuseUnloadedCssImage(url, label) {
|
|
46
|
+
if (!recordNames(loadedResources, url, document.baseURI)) {
|
|
47
|
+
fail('IMAGE_NOT_LOADED', `${label}: the page has not finished loading ${url}`);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
/** An <img> that has not finished loading (or failed) refuses. */
|
|
51
|
+
export function refuseUnloadedImg(image, label) {
|
|
52
|
+
if (!image.complete || image.naturalWidth === 0) {
|
|
53
|
+
fail('IMAGE_NOT_LOADED', `${label} has not finished loading`);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
function scratch(width, height) {
|
|
57
|
+
return scratchCanvas(width, height, 'an image check');
|
|
58
|
+
}
|
|
59
|
+
/** The image's pixels at its natural size, or null when the page may not read them. */
|
|
60
|
+
function readPixels(image, width, height) {
|
|
61
|
+
const { canvas, context } = scratch(width, height);
|
|
62
|
+
try {
|
|
63
|
+
context.drawImage(image, 0, 0, width, height);
|
|
64
|
+
return context.getImageData(0, 0, width, height);
|
|
65
|
+
}
|
|
66
|
+
catch (error) {
|
|
67
|
+
if (error instanceof DOMException && error.name === 'SecurityError')
|
|
68
|
+
return null;
|
|
69
|
+
throw error;
|
|
70
|
+
}
|
|
71
|
+
finally {
|
|
72
|
+
releaseCanvas(canvas);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
function samePixels(a, b) {
|
|
76
|
+
if (a.width !== b.width || a.height !== b.height)
|
|
77
|
+
return false;
|
|
78
|
+
const left = new Uint32Array(a.data.buffer);
|
|
79
|
+
const right = new Uint32Array(b.data.buffer);
|
|
80
|
+
for (let index = 0; index < left.length; index++)
|
|
81
|
+
if (left[index] !== right[index])
|
|
82
|
+
return false;
|
|
83
|
+
return true;
|
|
84
|
+
}
|
|
85
|
+
function pngOf(pixels) {
|
|
86
|
+
const { canvas, context } = scratch(pixels.width, pixels.height);
|
|
87
|
+
try {
|
|
88
|
+
context.putImageData(pixels, 0, 0);
|
|
89
|
+
return canvas.toDataURL('image/png');
|
|
90
|
+
}
|
|
91
|
+
finally {
|
|
92
|
+
releaseCanvas(canvas);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
async function decodeFetched(bytes, mime) {
|
|
96
|
+
try {
|
|
97
|
+
return await createImageBitmap(new Blob([bytes], { type: mime }));
|
|
98
|
+
}
|
|
99
|
+
catch {
|
|
100
|
+
return fail('RESOURCE_TYPE_MISMATCH', 'a fetched image could not be decoded');
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
function loadImage(url) {
|
|
104
|
+
return new Promise((resolve) => {
|
|
105
|
+
const image = new Image();
|
|
106
|
+
image.decoding = 'sync';
|
|
107
|
+
// Cross-origin, only a CORS load can be read to compare; one the server
|
|
108
|
+
// does not allow simply fails to load and refuses.
|
|
109
|
+
if (new URL(url, document.baseURI).origin !== location.origin)
|
|
110
|
+
image.crossOrigin = 'anonymous';
|
|
111
|
+
image.onload = () => resolve(image);
|
|
112
|
+
image.onerror = () => resolve(null);
|
|
113
|
+
image.src = url;
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* The data: URL to embed for a fetched image, tied to what the page shows.
|
|
118
|
+
* `pageImage` is the page's own <img> when there is one; for a CSS image a
|
|
119
|
+
* fresh Image of the same URL stands in for it.
|
|
120
|
+
*/
|
|
121
|
+
/** Only PNG and JPEG bytes, and no animated PNG (the page shows its frames, the cover one). */
|
|
122
|
+
export function checkImageBytes(bytes, mime, url) {
|
|
123
|
+
const png = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];
|
|
124
|
+
const isPng = png.every((byte, index) => bytes[index] === byte);
|
|
125
|
+
const isJpeg = bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff;
|
|
126
|
+
if (mime === 'image/png' ? !isPng : !isJpeg) {
|
|
127
|
+
fail('RESOURCE_TYPE_MISMATCH', `${url}: its bytes are not the ${mime} it is labelled`);
|
|
128
|
+
}
|
|
129
|
+
if (!isPng)
|
|
130
|
+
return;
|
|
131
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
132
|
+
for (let at = 8; at + 8 <= bytes.length;) {
|
|
133
|
+
const length = view.getUint32(at);
|
|
134
|
+
const type = String.fromCharCode(bytes[at + 4], bytes[at + 5], bytes[at + 6], bytes[at + 7]);
|
|
135
|
+
if (type === 'acTL')
|
|
136
|
+
fail('RESOURCE_TYPE_MISMATCH', `${url}: an animated PNG`);
|
|
137
|
+
if (type === 'IDAT' || type === 'IEND')
|
|
138
|
+
return;
|
|
139
|
+
at += 12 + length;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
export async function pageTiedImage(url, fetched, pageImage) {
|
|
143
|
+
// A CSS image has no element of its own to read: its stand-in is another
|
|
144
|
+
// load, which for a response that may not be reused is new bytes, not the
|
|
145
|
+
// ones the page decoded.
|
|
146
|
+
if (!pageImage && fetched.uncacheable) {
|
|
147
|
+
fail('IMAGE_CHANGED', `${url} may not be reused (Cache-Control), so the page's copy cannot be matched`);
|
|
148
|
+
}
|
|
149
|
+
const bitmap = await decodeFetched(fetched.bytes, fetched.mime);
|
|
150
|
+
try {
|
|
151
|
+
const page = pageImage ?? (await loadImage(url));
|
|
152
|
+
if (!page || page.naturalWidth === 0) {
|
|
153
|
+
fail('IMAGE_NOT_LOADED', `${url} does not load in this page`);
|
|
154
|
+
}
|
|
155
|
+
const width = page.naturalWidth;
|
|
156
|
+
const height = page.naturalHeight;
|
|
157
|
+
if (width * height > MAX_COMPARED_PIXELS) {
|
|
158
|
+
fail('RESOURCE_TOO_LARGE', `${url} is too large to check (${width}x${height})`);
|
|
159
|
+
}
|
|
160
|
+
const shown = readPixels(page, width, height);
|
|
161
|
+
if (!shown) {
|
|
162
|
+
fail('IMAGE_NOT_READABLE', `${url}: the page's copy of this image cannot be read to compare (cross-origin without CORS)`);
|
|
163
|
+
}
|
|
164
|
+
if (bitmap.width !== width || bitmap.height !== height) {
|
|
165
|
+
fail('IMAGE_CHANGED', `${url} is ${bitmap.width}x${bitmap.height} now, ${width}x${height} on the page`);
|
|
166
|
+
}
|
|
167
|
+
const copy = readPixels(bitmap, width, height);
|
|
168
|
+
if (copy && samePixels(shown, copy))
|
|
169
|
+
return fetched.dataUrl;
|
|
170
|
+
// The fetched copy is not what the page shows. The page's own <img> is:
|
|
171
|
+
// embed its pixels. A CSS image's stand-in is only another load, so there
|
|
172
|
+
// is nothing certain to embed.
|
|
173
|
+
if (pageImage)
|
|
174
|
+
return pngOf(shown);
|
|
175
|
+
return fail('IMAGE_CHANGED', `${url} returned different pixels than the page shows`);
|
|
176
|
+
}
|
|
177
|
+
finally {
|
|
178
|
+
bitmap.close();
|
|
179
|
+
}
|
|
180
|
+
}
|