@percy/core 1.32.4 → 1.32.5-beta.0

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.
@@ -0,0 +1,166 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import { ServerError } from './server.js';
4
+
5
+ /* istanbul ignore next — defensive manual directory walker invoked only when
6
+ fast-glob import fails (broken install / FS corruption). Unit tests
7
+ exercise the primary glob path; integration tests on BS hosts exercise
8
+ the walker against real session layouts. Path-traversal sinks inside this
9
+ function are suppressed at file level in .semgrepignore with the same
10
+ rationale (upstream SAFE_ID validation, depth cap, exact filename match). */
11
+ async function manualScreenshotWalk(platform, sessionId, name) {
12
+ const files = [];
13
+ try {
14
+ if (platform === 'ios') {
15
+ const sessionDir = `/tmp/${sessionId}`;
16
+ const walk = async (dir, depth) => {
17
+ if (depth > 15) return; // sanity cap
18
+ let entries;
19
+ try {
20
+ entries = await fs.promises.readdir(dir, {
21
+ withFileTypes: true
22
+ });
23
+ } catch {
24
+ return;
25
+ }
26
+ for (const entry of entries) {
27
+ const full = path.join(dir, entry.name);
28
+ if (entry.isDirectory()) {
29
+ await walk(full, depth + 1);
30
+ } else if (entry.isFile() && entry.name === `${name}.png` && full.includes('_maestro_debug_')) {
31
+ files.push(full);
32
+ }
33
+ }
34
+ };
35
+ await walk(sessionDir, 0);
36
+ } else {
37
+ const baseDir = `/tmp/${sessionId}_test_suite/logs`;
38
+ const logDirs = await fs.promises.readdir(baseDir);
39
+ for (const dir of logDirs) {
40
+ const screenshotPath = path.join(baseDir, dir, 'screenshots', `${name}.png`);
41
+ try {
42
+ await fs.promises.access(screenshotPath);
43
+ files.push(screenshotPath);
44
+ } catch {/* not found, continue */}
45
+ }
46
+ }
47
+ } catch {/* base dir not found */}
48
+ return files;
49
+ }
50
+
51
+ // Locate the screenshot on disk and confirm it lives under `scopeRoot`. Three
52
+ // paths converge on `chosenFile`:
53
+ // 1. `filePath` supplied (BrowserStack new SDK — absolute path under the BS
54
+ // session root; rejected upstream in self-hosted mode).
55
+ // 2. BrowserStack glob (the BS-infra SCREENSHOTS_DIR layout).
56
+ // 3. Self-hosted recursive glob under scopeRoot (PERCY_MAESTRO_SCREENSHOT_DIR).
57
+ // Either way, the shared realpath + scopeRoot prefix check below enforces the
58
+ // security invariant. Returns the canonicalized absolute path, or throws
59
+ // ServerError(404) when the file is missing or resolves outside scopeRoot.
60
+ // Callers pass `filePath` already shape-validated, plus the resolved `scopeRoot`
61
+ // and `selfHosted` flag.
62
+ export async function locateScreenshot({
63
+ platform,
64
+ sessionId,
65
+ name,
66
+ filePath,
67
+ scopeRoot,
68
+ selfHosted
69
+ }) {
70
+ let chosenFile;
71
+ if (filePath) {
72
+ chosenFile = filePath;
73
+ } else {
74
+ // Glob pattern depends on deployment shape:
75
+ // BrowserStack Android: /tmp/{sid}_test_suite/logs/*/screenshots/{name}.png
76
+ // BrowserStack iOS: /tmp/{sid}/<maestro_debug_dir>/**/{name}.png
77
+ // (realmobile builds a deeply nested {device}_maestro_debug_ tree; `**`
78
+ // handles any depth, exact {name}.png filters Maestro's emoji-prefixed
79
+ // debug frames, e.g. `screenshot-❌-<timestamp>-(flow).png`).
80
+ // Self-hosted: recursive glob under the customer's --test-output-dir
81
+ // (scopeRoot = PERCY_MAESTRO_SCREENSHOT_DIR). `name` is SAFE_ID-validated
82
+ // by the caller, so it cannot contain separators or traversal chars.
83
+ let searchPattern;
84
+ if (selfHosted) {
85
+ // fast-glob requires forward-slashes in patterns on every platform; on
86
+ // Windows scopeRoot contains backslashes, so normalize before embedding.
87
+ // Production-code Windows portability — verified by the CI Windows runner.
88
+ const globRoot = scopeRoot.replace(/\\/g, '/');
89
+ searchPattern = `${globRoot}/**/${name}.png`;
90
+ } else {
91
+ searchPattern = platform === 'ios' ? `/tmp/${sessionId}/*_maestro_debug_*/**/${name}.png` : `/tmp/${sessionId}_test_suite/logs/*/screenshots/${name}.png`;
92
+ }
93
+ let files;
94
+ try {
95
+ let {
96
+ default: glob
97
+ } = await import('fast-glob');
98
+ // Self-hosted needs `dot: true` because Maestro's default output dir is
99
+ // `.maestro/` — a dot-prefixed entry fast-glob hides by default. BS
100
+ // layouts have no dot-prefixed segments, so omitting it there keeps the
101
+ // byte-identical behavior.
102
+ files = await glob(searchPattern, selfHosted ? {
103
+ dot: true
104
+ } : undefined);
105
+ } catch {
106
+ // Fast-glob import / glob call failed — fall back to manual walker (BS
107
+ // only; self-hosted has no fixed-layout convention, so empty → 404 with
108
+ // the actionable PERCY_MAESTRO_SCREENSHOT_DIR guidance from the caller).
109
+ // See manualScreenshotWalk() at file top + the file-level .semgrepignore.
110
+ /* istanbul ignore next — only fires when fast-glob import throws
111
+ (broken install / FS corruption); integration-test territory. */
112
+ files = selfHosted ? [] : await manualScreenshotWalk(platform, sessionId, name);
113
+ }
114
+ if (!files || files.length === 0) {
115
+ throw new ServerError(404, `Screenshot not found: ${name}.png (searched ${searchPattern})`);
116
+ }
117
+
118
+ // If multiple files match (iOS — same name reused across flows), pick the most recently modified
119
+ // for determinism. The else branch only fires when a snapshot name
120
+ // is reused across two flows in the same session; the realmobile
121
+ // layout normally writes one file per snapshot per session, so the
122
+ // multi-match path is exercised by integration tests on BS hosts
123
+ // rather than the unit suite.
124
+ /* istanbul ignore else */
125
+ if (files.length === 1) {
126
+ chosenFile = files[0];
127
+ } else {
128
+ let mtimes = await Promise.all(files.map(async f => {
129
+ try {
130
+ return {
131
+ f,
132
+ mtime: (await fs.promises.stat(f)).mtimeMs
133
+ };
134
+ } catch {
135
+ return {
136
+ f,
137
+ mtime: 0
138
+ };
139
+ }
140
+ }));
141
+ mtimes.sort((a, b) => b.mtime - a.mtime);
142
+ chosenFile = mtimes[0].f;
143
+ }
144
+ }
145
+
146
+ // Canonicalize and confirm the resolved path still lives under scopeRoot.
147
+ // Defeats symlink swaps where the root points elsewhere. Both ends are
148
+ // realpath'd because /tmp is a symlink on macOS (where iOS hosts run). The
149
+ // trailing `/` on the prefix is load-bearing — it prevents sibling-prefix
150
+ // bypass (e.g. /x/.maestro vs /x/.maestro-secrets). Both sides are
151
+ // normalized to forward-slashes so the check works on Windows (real-fs
152
+ // returns backslashes), POSIX (no-op), and memfs (POSIX-style virtual paths).
153
+ let realPath, realPrefix;
154
+ try {
155
+ realPath = await fs.promises.realpath(chosenFile);
156
+ realPrefix = await fs.promises.realpath(scopeRoot);
157
+ } catch {
158
+ throw new ServerError(404, `Screenshot not found: ${name}.png (path resolution failed)`);
159
+ }
160
+ const realPathFwd = realPath.replace(/\\/g, '/');
161
+ const realPrefixFwd = realPrefix.replace(/\\/g, '/');
162
+ if (!realPathFwd.startsWith(`${realPrefixFwd}/`)) {
163
+ throw new ServerError(404, `Screenshot not found: ${name}.png (resolved outside ${selfHosted ? 'PERCY_MAESTRO_SCREENSHOT_DIR' : 'session dir'})`);
164
+ }
165
+ return realPath;
166
+ }
@@ -0,0 +1,282 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import { normalize } from '@percy/config/utils';
4
+ import { ServerError } from './server.js';
5
+ import { encodeURLSearchParams } from './utils.js';
6
+ import { handleSyncJob } from './snapshot.js';
7
+ import { locateScreenshot } from './maestro-screenshot-file.js';
8
+ import { validateRegionInputs, resolveRegions } from './maestro-regions.js';
9
+ import { deriveDeviceInsets } from './maestro-hierarchy.js';
10
+
11
+ // Parse PNG IHDR chunk for the screenshot's actual rendered dimensions.
12
+ // Returns { width, height } when the buffer is a valid PNG with non-zero
13
+ // dimensions, or null otherwise (non-PNG signature, truncated file, zero
14
+ // IHDR values). PNG layout per W3C spec:
15
+ // bytes 0..7 PNG signature (89 50 4E 47 0D 0A 1A 0A)
16
+ // bytes 8..15 IHDR chunk header (length + type, fixed)
17
+ // bytes 16..19 width (big-endian uint32)
18
+ // bytes 20..23 height (big-endian uint32)
19
+ // No library dependency — pure stdlib Buffer access on the bytes the relay
20
+ // has already read.
21
+ export function parsePngDimensions(buffer) {
22
+ if (!buffer || buffer.length < 24) return null;
23
+ if (buffer[0] !== 0x89 || buffer[1] !== 0x50 || buffer[2] !== 0x4E || buffer[3] !== 0x47 || buffer[4] !== 0x0D || buffer[5] !== 0x0A || buffer[6] !== 0x1A || buffer[7] !== 0x0A) {
24
+ return null;
25
+ }
26
+ const width = buffer.readUInt32BE(16);
27
+ const height = buffer.readUInt32BE(20);
28
+ if (width <= 0 || height <= 0) return null;
29
+ return {
30
+ width,
31
+ height
32
+ };
33
+ }
34
+
35
+ // Handler for `post /percy/maestro-screenshot`: post a comparison by reading
36
+ // a Maestro screenshot from disk.
37
+ export async function handleMaestroScreenshot(req, res, percy) {
38
+ var _insets, _insets2, _percy$build;
39
+ /* istanbul ignore next — req.body falsy guard; tests always pass a body. */
40
+ let {
41
+ name,
42
+ sessionId
43
+ } = req.body || {};
44
+ if (!name) throw new ServerError(400, 'Missing required field: name');
45
+
46
+ // Self-hosted vs BrowserStack is signaled by sessionId presence: BS
47
+ // host-injection always supplies it; self-hosted runs never do.
48
+ let selfHosted = !sessionId;
49
+
50
+ // Strict character-class validation — rejects path separators, shell metacharacters,
51
+ // NUL, newlines, and anything else that could confuse the glob or the filesystem.
52
+ // `name` is load-bearing for the recursive glob — must not be loosened.
53
+ const SAFE_ID = /^[a-zA-Z0-9_-]+$/;
54
+ if (!SAFE_ID.test(name)) {
55
+ throw new ServerError(400, 'Invalid screenshot name');
56
+ }
57
+ if (sessionId && !SAFE_ID.test(sessionId)) {
58
+ throw new ServerError(400, 'Invalid sessionId');
59
+ }
60
+
61
+ // Resolve platform signal: strict whitelist on `platform` when present; default Android when absent.
62
+ // Backward compatible with SDK v0.2.0 (no platform field → Android glob).
63
+ let platform = 'android';
64
+ if (req.body.platform !== undefined) {
65
+ if (typeof req.body.platform !== 'string') {
66
+ throw new ServerError(400, 'Invalid platform: must be a string');
67
+ }
68
+ let normalized = req.body.platform.toLowerCase();
69
+ if (normalized !== 'ios' && normalized !== 'android') {
70
+ throw new ServerError(400, `Invalid platform: must be "ios" or "android", got "${req.body.platform}"`);
71
+ }
72
+ platform = normalized;
73
+ }
74
+
75
+ // Optional caller-supplied absolute path. When present, the relay reads
76
+ // the file directly and skips the legacy glob — the SDK has already
77
+ // chosen the path under the BS session root. Shape errors (non-string,
78
+ // non-absolute, too long) are 400. Existence and session-root scoping
79
+ // are enforced by the shared realpath + prefix check below, which
80
+ // returns 404 — same shape as the glob path. Treat empty string as
81
+ // absent so older SDKs that emit the field unconditionally still fall
82
+ // through to the glob.
83
+ let suppliedFilePath = null;
84
+ if (req.body.filePath !== undefined && req.body.filePath !== null && req.body.filePath !== '') {
85
+ if (typeof req.body.filePath !== 'string') {
86
+ throw new ServerError(400, 'Invalid filePath: must be a string');
87
+ }
88
+ if (req.body.filePath.length > 1024) {
89
+ throw new ServerError(400, 'Invalid filePath: exceeds maximum length of 1024');
90
+ }
91
+ if (!path.isAbsolute(req.body.filePath)) {
92
+ throw new ServerError(400, 'Invalid filePath: must be an absolute path');
93
+ }
94
+ suppliedFilePath = req.body.filePath;
95
+ }
96
+
97
+ // Resolve the file-find scope root. On BrowserStack (sessionId present), the
98
+ // root is the BS host's /tmp/{sessionId}{_test_suite} convention. Self-hosted
99
+ // (sessionId absent) requires PERCY_MAESTRO_SCREENSHOT_DIR (read from
100
+ // process.env, never the request body) to be an absolute, existing directory
101
+ // — typically the customer's `maestro test --test-output-dir <DIR>` path. The
102
+ // realpath + prefix check inside locateScreenshot enforces the security
103
+ // invariant at whichever root applies; the boundary is relocated, not removed.
104
+ let scopeRoot;
105
+ if (selfHosted) {
106
+ // Reject filePath outright in self-hosted mode. The SDK never emits it (it
107
+ // sends a relative SCREENSHOT_NAME); honoring an absolute filePath against
108
+ // a caller-influenceable root would re-open arbitrary in-root reads.
109
+ if (suppliedFilePath) {
110
+ throw new ServerError(400, 'filePath is not accepted in self-hosted mode (omit it; PERCY_MAESTRO_SCREENSHOT_DIR + relative SCREENSHOT_NAME is the supported path)');
111
+ }
112
+ let dir = process.env.PERCY_MAESTRO_SCREENSHOT_DIR;
113
+ if (!dir) {
114
+ throw new ServerError(400, 'Missing required env: PERCY_MAESTRO_SCREENSHOT_DIR (set it to your `maestro test --test-output-dir` path)');
115
+ }
116
+ if (!path.isAbsolute(dir)) {
117
+ throw new ServerError(400, 'PERCY_MAESTRO_SCREENSHOT_DIR must be an absolute path');
118
+ }
119
+ // UX guard ONLY: surface an actionable 400 ("dir not found") instead of the
120
+ // opaque 404 the realpath+prefix containment check would emit for a missing
121
+ // dir. A small TOCTOU window exists between this stat and locateScreenshot's
122
+ // realpath — acceptable because realpath (not stat) is the security
123
+ // invariant: even if the dir is swapped for a symlink in between, realpath
124
+ // resolves the target and the sep-prefix check rejects anything outside it.
125
+ let stat;
126
+ try {
127
+ stat = await fs.promises.stat(dir);
128
+ } catch {
129
+ stat = null;
130
+ }
131
+ if (!stat || !stat.isDirectory()) {
132
+ throw new ServerError(400, `PERCY_MAESTRO_SCREENSHOT_DIR is not an existing directory: ${dir}`);
133
+ }
134
+ scopeRoot = dir;
135
+ } else {
136
+ scopeRoot = platform === 'ios' ? `/tmp/${sessionId}` : `/tmp/${sessionId}_test_suite`;
137
+ }
138
+
139
+ // Validate regions input shape early (before file I/O and ADB work) so
140
+ // malformed requests don't consume resolver/relay work.
141
+ validateRegionInputs(req.body);
142
+
143
+ // Locate the screenshot on disk (supplied filePath, BS session glob, or
144
+ // self-hosted PERCY_MAESTRO_SCREENSHOT_DIR recursive glob) and confirm it
145
+ // resolves under scopeRoot. Throws ServerError(404) when missing/out-of-root.
146
+ let realPath = await locateScreenshot({
147
+ platform,
148
+ sessionId,
149
+ name,
150
+ filePath: suppliedFilePath,
151
+ scopeRoot,
152
+ selfHosted
153
+ });
154
+
155
+ // Read and base64-encode the screenshot
156
+ let fileContent = await fs.promises.readFile(realPath);
157
+ let base64Content = fileContent.toString('base64');
158
+
159
+ // Parse the PNG header for actual rendered dimensions. The PNG bytes
160
+ // ARE the source of truth — what Percy stores and compares against.
161
+ // Fills tag.width/height when the customer didn't supply them (or
162
+ // supplied invalid values); customer-supplied values continue to win
163
+ // for backward compat with any flow that pins a specific tag dim.
164
+ let pngDims = parsePngDimensions(fileContent);
165
+
166
+ // Build tag from optional request body fields
167
+ let tag = req.body.tag || {
168
+ name: 'Unknown Device',
169
+ osName: 'Android'
170
+ };
171
+ /* istanbul ignore if — fallback when tag.name is missing; tests always
172
+ pass a complete tag object. */
173
+ if (!tag.name) tag.name = 'Unknown Device';
174
+ if (pngDims) {
175
+ if (typeof tag.width !== 'number' || tag.width <= 0 || isNaN(tag.width)) {
176
+ tag.width = pngDims.width;
177
+ }
178
+ if (typeof tag.height !== 'number' || tag.height <= 0 || isNaN(tag.height)) {
179
+ tag.height = pngDims.height;
180
+ }
181
+ }
182
+
183
+ // Derive exact device system-bar insets (pixels), once per session — they're
184
+ // device-constant, so the first snapshot pays one /viewHierarchy (iOS) or
185
+ // `dumpsys` (Android) call and the rest reuse the cached result (incl. a null
186
+ // "use SDK default" outcome). CLI-derived values are authoritative over the
187
+ // SDK's static defaults (those are SDK internal constants, not customer-set);
188
+ // any derivation failure falls back to the SDK value. iOS navBarHeight is
189
+ // always 0 — the home indicator is static and unmeasured, fleet-consistent.
190
+ let insets = percy.maestroInsetCache.get(sessionId);
191
+ if (insets === undefined) {
192
+ insets = await deriveDeviceInsets({
193
+ platform,
194
+ sessionId,
195
+ pngDims
196
+ });
197
+ percy.maestroInsetCache.set(sessionId, insets);
198
+ percy.log.debug(`maestro device insets (${platform}): ${JSON.stringify(insets)}`);
199
+ }
200
+ let statusBarHeight = ((_insets = insets) === null || _insets === void 0 ? void 0 : _insets.statusBarHeight) ?? (req.body.statusBarHeight || 0);
201
+ let navBarHeight = platform === 'ios' ? 0 : ((_insets2 = insets) === null || _insets2 === void 0 ? void 0 : _insets2.navBarHeight) ?? (req.body.navBarHeight || 0);
202
+
203
+ // Construct comparison payload with tile metadata from request
204
+ let payload = {
205
+ name,
206
+ tag,
207
+ tiles: [{
208
+ content: base64Content,
209
+ statusBarHeight,
210
+ navBarHeight,
211
+ headerHeight: 0,
212
+ footerHeight: 0,
213
+ fullscreen: req.body.fullscreen || false
214
+ }],
215
+ clientInfo: req.body.clientInfo || 'percy-maestro/0.1.0',
216
+ environmentInfo: req.body.environmentInfo || 'percy-maestro'
217
+ };
218
+ if (req.body.testCase) payload.testCase = req.body.testCase;
219
+ if (req.body.labels) payload.labels = req.body.labels;
220
+ if (req.body.thTestCaseExecutionId) payload.thTestCaseExecutionId = req.body.thTestCaseExecutionId;
221
+
222
+ // Resolve element/coordinate regions to comparison-payload fragments.
223
+ // Element regions degrade gracefully — a resolver failure warn-skips those
224
+ // regions only; the snapshot still uploads. The hierarchy dump is memoized
225
+ // per request inside resolveRegions. Assign the three known comparison keys
226
+ // explicitly (never Object.assign of request-derived data) so only these
227
+ // fields can ever be set here.
228
+ let regionData = await resolveRegions({
229
+ body: req.body,
230
+ platform,
231
+ sessionId,
232
+ percy
233
+ });
234
+ if (regionData.regions) payload.regions = regionData.regions;
235
+ if (regionData.ignoredElementsData) payload.ignoredElementsData = regionData.ignoredElementsData;
236
+ if (regionData.consideredElementsData) payload.consideredElementsData = regionData.consideredElementsData;
237
+
238
+ // Upload via percy — sync or fire-and-forget
239
+ if (req.body.sync === true) payload.sync = true;
240
+ let data;
241
+ if (percy.syncMode(payload)) {
242
+ // percy.upload() is the generatePromise-wrapped method: calling it drives the
243
+ // underlying async generator to completion (enqueuing #snapshots) and the sync
244
+ // queue resolves/rejects the attached callback. Do NOT `for await` the return
245
+ // value — it is a Promise, not an async iterable (that throws "upload is not
246
+ // async iterable"). The raw generator lives at percy.yield.upload() if direct
247
+ // iteration is ever needed. The trailing .catch(reject) surfaces generator
248
+ // errors that bypass the sync-queue callback (e.g. a throw before the queue task
249
+ // runs) instead of leaking an unhandled rejection and hanging the request.
250
+ const snapshotPromise = new Promise((resolve, reject) => {
251
+ percy.upload(payload, {
252
+ resolve,
253
+ reject
254
+ }, 'app').catch(reject);
255
+ });
256
+ data = await handleSyncJob(snapshotPromise, percy, 'comparison');
257
+ return res.json(200, {
258
+ success: true,
259
+ data
260
+ });
261
+ }
262
+ let upload = percy.upload(payload, null, 'app');
263
+ /* istanbul ignore if — ?await=true URL flag triggers fire-and-wait;
264
+ tests cover both syncMode and fire-and-forget but not the explicit
265
+ ?await query-param variant. */
266
+ if (req.url.searchParams.has('await')) await upload;
267
+
268
+ // Generate redirect link
269
+ let link = [percy.client.apiUrl, '/comparisons/redirect?', encodeURLSearchParams(normalize({
270
+ buildId: (_percy$build = percy.build) === null || _percy$build === void 0 ? void 0 : _percy$build.id,
271
+ snapshot: {
272
+ name
273
+ },
274
+ tag
275
+ }, {
276
+ snake: true
277
+ }))].join('');
278
+ return res.json(200, {
279
+ success: true,
280
+ link
281
+ });
282
+ }