@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.
package/dist/api.js CHANGED
@@ -2,13 +2,13 @@ import fs from 'fs';
2
2
  import path, { dirname, resolve } from 'path';
3
3
  import logger from '@percy/logger';
4
4
  import { normalize } from '@percy/config/utils';
5
- import { getPackageJSON, Server, percyAutomateRequestHandler, percyBuildEventHandler, computeResponsiveWidths } from './utils.js';
6
- import { ServerError } from './server.js';
5
+ import { getPackageJSON, Server, percyAutomateRequestHandler, percyBuildEventHandler, computeResponsiveWidths, encodeURLSearchParams } from './utils.js';
6
+ import { ServerError, isLoopbackOrigin } from './server.js';
7
7
  import WebdriverUtils from '@percy/webdriver-utils';
8
8
  import { handleSyncJob } from './snapshot.js';
9
- import { dump as maestroDump, firstMatch as maestroFirstMatch, SELECTOR_KEYS_WHITELIST, getMaestroHierarchyDrift } from './maestro-hierarchy.js';
10
- import Busboy from 'busboy';
11
- import { Readable } from 'stream';
9
+ import { getMaestroHierarchyDrift } from './maestro-hierarchy.js';
10
+ import { handleComparisonUpload } from './comparison-upload.js';
11
+ import { handleMaestroScreenshot } from './maestro-screenshot.js';
12
12
  // Previously, we used `createRequire(import.meta.url).resolve` to resolve the path to the module.
13
13
  // This approach relied on `createRequire`, which is Node.js-specific and less compatible with modern ESM (ECMAScript Module) standards.
14
14
  // This was leading to hard coded paths when CLI is used as a dependency in another project.
@@ -31,11 +31,6 @@ export const getPercyDomPath = url => {
31
31
  // Resolved path for PERCY_DOM
32
32
  export const PERCY_DOM = getPercyDomPath(import.meta.url);
33
33
 
34
- // Returns a URL encoded string of nested query params
35
- function encodeURLSearchParams(subj, prefix) {
36
- return typeof subj === 'object' ? Object.entries(subj).map(([key, value]) => encodeURLSearchParams(value, prefix ? `${prefix}[${key}]` : key)).join('&') : `${prefix}=${encodeURIComponent(subj)}`;
37
- }
38
-
39
34
  // Walks the config schema and collects dot-paths of any fields marked `httpReadOnly: true`
40
35
  // that are present in `body`. Driving this from the schema means new HTTP-blocked fields
41
36
  // only need a one-line annotation next to their definition — no list to keep in sync here.
@@ -87,172 +82,20 @@ function stripBlockedConfigFields(body, log) {
87
82
  return _applyHttpReadOnlyStripping(body, findHttpReadOnlyPaths(body, ROOT_CONFIG_SCHEMA), log);
88
83
  }
89
84
 
90
- // Parse PNG IHDR chunk for the screenshot's actual rendered dimensions.
91
- // Returns { width, height } when the buffer is a valid PNG with non-zero
92
- // dimensions, or null otherwise (non-PNG signature, truncated file, zero
93
- // IHDR values). PNG layout per W3C spec:
94
- // bytes 0..7 PNG signature (89 50 4E 47 0D 0A 1A 0A)
95
- // bytes 8..15 IHDR chunk header (length + type, fixed)
96
- // bytes 16..19 width (big-endian uint32)
97
- // bytes 20..23 height (big-endian uint32)
98
- // No library dependency — pure stdlib Buffer access on the bytes the relay
99
- // has already read.
100
- export function parsePngDimensions(buffer) {
101
- if (!buffer || buffer.length < 24) return null;
102
- 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) {
103
- return null;
85
+ // Reject state-changing requests that carry a cross-origin (non-loopback) Origin
86
+ // header. The local server is unauthenticated by design (SDKs post to it), so
87
+ // this blocks a malicious website the user is visiting from driving sensitive
88
+ // endpoints — live config mutation or stopping the build — via the browser
89
+ // (CWE-352 / CWE-306, PER-8600/8601). Node SDK clients send no Origin header and
90
+ // are unaffected; loopback browser tooling (any localhost port) is allowed.
91
+ function assertNotCrossOrigin(req) {
92
+ let origin = req.headers.origin;
93
+ if (origin && !isLoopbackOrigin(origin)) {
94
+ throw new ServerError(403, 'Cross-origin requests are not allowed on this endpoint');
104
95
  }
105
- const width = buffer.readUInt32BE(16);
106
- const height = buffer.readUInt32BE(20);
107
- if (width <= 0 || height <= 0) return null;
108
- return {
109
- width,
110
- height
111
- };
112
96
  }
113
97
 
114
98
  // Create a Percy CLI API server instance
115
- /* istanbul ignore next — defensive manual directory walker invoked only when
116
- fast-glob import fails (broken install / FS corruption). Unit tests
117
- exercise the primary glob path; integration tests on BS hosts exercise
118
- the walker against real session layouts. Path-traversal sinks inside this
119
- function are suppressed at file level in .semgrepignore with the same
120
- rationale (upstream SAFE_ID validation, depth cap, exact filename match). */
121
- async function manualScreenshotWalk(platform, sessionId, name) {
122
- const files = [];
123
- try {
124
- if (platform === 'ios') {
125
- const sessionDir = `/tmp/${sessionId}`;
126
- const walk = async (dir, depth) => {
127
- if (depth > 15) return; // sanity cap
128
- let entries;
129
- try {
130
- entries = await fs.promises.readdir(dir, {
131
- withFileTypes: true
132
- });
133
- } catch {
134
- return;
135
- }
136
- for (const entry of entries) {
137
- const full = path.join(dir, entry.name);
138
- if (entry.isDirectory()) {
139
- await walk(full, depth + 1);
140
- } else if (entry.isFile() && entry.name === `${name}.png` && full.includes('_maestro_debug_')) {
141
- files.push(full);
142
- }
143
- }
144
- };
145
- await walk(sessionDir, 0);
146
- } else {
147
- const baseDir = `/tmp/${sessionId}_test_suite/logs`;
148
- const logDirs = await fs.promises.readdir(baseDir);
149
- for (const dir of logDirs) {
150
- const screenshotPath = path.join(baseDir, dir, 'screenshots', `${name}.png`);
151
- try {
152
- await fs.promises.access(screenshotPath);
153
- files.push(screenshotPath);
154
- } catch {/* not found, continue */}
155
- }
156
- }
157
- } catch {/* base dir not found */}
158
- return files;
159
- }
160
-
161
- /* istanbul ignore next — multipart /percy/comparison/upload handler;
162
- exercises Busboy stream parsing + PNG magic-byte validation + base64
163
- encoding + percy.upload. Integration-tested via the regression suite
164
- (real multipart POST) rather than the unit suite, which would require
165
- constructing valid multipart bodies. */
166
- async function handleComparisonUpload(req, res, percy) {
167
- var _percy$build;
168
- const MAX_FILE_SIZE = 50 * 1024 * 1024; // 50MB
169
- const PNG_MAGIC_BYTES = Buffer.from([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]);
170
- let contentType = req.headers['content-type'] || '';
171
- if (!contentType.startsWith('multipart/form-data')) {
172
- throw new ServerError(400, 'Content-Type must be multipart/form-data');
173
- }
174
- if (!req.body) {
175
- throw new ServerError(400, 'Empty request body');
176
- }
177
- let fields = Object.create(null);
178
- let fileBuffer = null;
179
- await new Promise((resolve, reject) => {
180
- let bb = Busboy({
181
- headers: req.headers,
182
- limits: {
183
- fileSize: MAX_FILE_SIZE
184
- }
185
- });
186
- bb.on('file', (fieldname, stream, info) => {
187
- let chunks = [];
188
- stream.on('data', chunk => chunks.push(chunk));
189
- stream.on('limit', () => {
190
- reject(new ServerError(413, 'File size exceeds maximum of 50MB'));
191
- });
192
- stream.on('end', () => {
193
- if (fieldname === 'screenshot') {
194
- fileBuffer = Buffer.concat(chunks);
195
- }
196
- });
197
- });
198
- bb.on('field', (fieldname, value) => {
199
- if (['name', 'tag', 'clientInfo', 'environmentInfo', 'testCase', 'labels'].includes(fieldname)) {
200
- fields[fieldname] = value;
201
- }
202
- });
203
- bb.on('close', resolve);
204
- bb.on('error', reject);
205
- let stream = Readable.from(req.body);
206
- stream.on('error', reject);
207
- stream.pipe(bb);
208
- });
209
- if (!fileBuffer) {
210
- throw new ServerError(400, 'Missing required file part: screenshot');
211
- }
212
- if (fileBuffer.length < 8 || !fileBuffer.subarray(0, 8).equals(PNG_MAGIC_BYTES)) {
213
- throw new ServerError(400, 'File is not a valid PNG image');
214
- }
215
- if (!fields.name) throw new ServerError(400, 'Missing required field: name');
216
- if (!fields.tag) throw new ServerError(400, 'Missing required field: tag');
217
- let tag;
218
- try {
219
- tag = JSON.parse(fields.tag);
220
- } catch {
221
- throw new ServerError(400, 'Invalid JSON in tag field');
222
- }
223
- let base64Content = fileBuffer.toString('base64');
224
- let payload = {
225
- name: fields.name,
226
- tag,
227
- tiles: [{
228
- content: base64Content,
229
- statusBarHeight: 0,
230
- navBarHeight: 0,
231
- headerHeight: 0,
232
- footerHeight: 0,
233
- fullscreen: false
234
- }],
235
- clientInfo: fields.clientInfo || '',
236
- environmentInfo: fields.environmentInfo || ''
237
- };
238
- if (fields.testCase) payload.testCase = fields.testCase;
239
- if (fields.labels) payload.labels = fields.labels;
240
- let upload = percy.upload(payload, null, 'app');
241
- if (req.url.searchParams.has('await')) await upload;
242
- let link = [percy.client.apiUrl, '/comparisons/redirect?', encodeURLSearchParams(normalize({
243
- buildId: (_percy$build = percy.build) === null || _percy$build === void 0 ? void 0 : _percy$build.id,
244
- snapshot: {
245
- name: payload.name
246
- },
247
- tag
248
- }, {
249
- snake: true
250
- }))].join('');
251
- return res.json(200, {
252
- success: true,
253
- link
254
- });
255
- }
256
99
  export function createPercyServer(percy, port) {
257
100
  let pkg = getPackageJSON(import.meta.url);
258
101
  let server = Server.createServer({
@@ -269,8 +112,13 @@ export function createPercyServer(percy, port) {
269
112
  } catch {}
270
113
  }
271
114
 
272
- // add version header
273
- res.setHeader('Access-Control-Expose-Headers', '*, X-Percy-Core-Version');
115
+ // Expose headers only to loopback origins, consistent with the CORS
116
+ // handler in server.js. Access-Control-Expose-Headers is inert without a
117
+ // matching Access-Control-Allow-Origin, so gating it here keeps the two
118
+ // layers aligned rather than emitting it unconditionally.
119
+ if (isLoopbackOrigin(req.headers.origin)) {
120
+ res.setHeader('Access-Control-Expose-Headers', '*, X-Percy-Core-Version');
121
+ }
274
122
 
275
123
  // skip or change api version header in testing mode
276
124
  if (((_percy$testing = percy.testing) === null || _percy$testing === void 0 ? void 0 : _percy$testing.version) !== false) {
@@ -298,8 +146,17 @@ export function createPercyServer(percy, port) {
298
146
  next = () => req.connection.destroy();
299
147
  }
300
148
 
149
+ // Block cross-origin browser requests to every state-changing route at a
150
+ // single choke point. CORS-safelisted content types (text/plain, form
151
+ // data) reach handlers with no preflight, but a cross-origin request
152
+ // always carries an Origin header, so gating every non-safe method here
153
+ // covers all present and future mutating routes. Read-only methods and
154
+ // same-host / no-Origin SDK callers are unaffected.
301
155
  // return json errors
302
- return next().catch(e => {
156
+ return Promise.resolve().then(() => {
157
+ if (!['GET', 'HEAD', 'OPTIONS'].includes(req.method)) assertNotCrossOrigin(req);
158
+ return next();
159
+ }).catch(e => {
303
160
  var _percy$testing6;
304
161
  return res.json(e.status ?? 500, {
305
162
  build: ((_percy$testing6 = percy.testing) === null || _percy$testing6 === void 0 ? void 0 : _percy$testing6.build) || percy.build,
@@ -350,6 +207,7 @@ export function createPercyServer(percy, port) {
350
207
  })
351
208
  // get or set config options
352
209
  .route(['get', 'post'], '/percy/config', async (req, res) => {
210
+ // POST mutation is blocked cross-origin by the general middleware above.
353
211
  let body = req.body && stripBlockedConfigFields(req.body, logger('core:server'));
354
212
  return res.json(200, {
355
213
  config: body ? percy.set(body) : percy.config,
@@ -412,9 +270,9 @@ export function createPercyServer(percy, port) {
412
270
  name,
413
271
  tag
414
272
  }) => {
415
- var _percy$build2;
273
+ var _percy$build;
416
274
  return [percy.client.apiUrl, '/comparisons/redirect?', encodeURLSearchParams(normalize({
417
- buildId: (_percy$build2 = percy.build) === null || _percy$build2 === void 0 ? void 0 : _percy$build2.id,
275
+ buildId: (_percy$build = percy.build) === null || _percy$build === void 0 ? void 0 : _percy$build.id,
418
276
  snapshot: {
419
277
  name
420
278
  },
@@ -439,554 +297,7 @@ export function createPercyServer(percy, port) {
439
297
  // post a comparison via multipart file upload
440
298
  .route('post', '/percy/comparison/upload', /* istanbul ignore next */(req, res) => handleComparisonUpload(req, res, percy))
441
299
  // post a comparison by reading a Maestro screenshot from disk
442
- .route('post', '/percy/maestro-screenshot', async (req, res) => {
443
- var _percy$build3;
444
- /* istanbul ignore next — req.body falsy guard; tests always pass a body. */
445
- let {
446
- name,
447
- sessionId
448
- } = req.body || {};
449
- if (!name) throw new ServerError(400, 'Missing required field: name');
450
-
451
- // Self-hosted vs BrowserStack is signaled by sessionId presence: BS
452
- // host-injection always supplies it; self-hosted runs never do.
453
- let selfHosted = !sessionId;
454
-
455
- // Strict character-class validation — rejects path separators, shell metacharacters,
456
- // NUL, newlines, and anything else that could confuse the glob or the filesystem.
457
- // `name` is load-bearing for the recursive glob — must not be loosened.
458
- const SAFE_ID = /^[a-zA-Z0-9_-]+$/;
459
- if (!SAFE_ID.test(name)) {
460
- throw new ServerError(400, 'Invalid screenshot name');
461
- }
462
- if (sessionId && !SAFE_ID.test(sessionId)) {
463
- throw new ServerError(400, 'Invalid sessionId');
464
- }
465
-
466
- // Resolve platform signal: strict whitelist on `platform` when present; default Android when absent.
467
- // Backward compatible with SDK v0.2.0 (no platform field → Android glob).
468
- let platform = 'android';
469
- if (req.body.platform !== undefined) {
470
- if (typeof req.body.platform !== 'string') {
471
- throw new ServerError(400, 'Invalid platform: must be a string');
472
- }
473
- let normalized = req.body.platform.toLowerCase();
474
- if (normalized !== 'ios' && normalized !== 'android') {
475
- throw new ServerError(400, `Invalid platform: must be "ios" or "android", got "${req.body.platform}"`);
476
- }
477
- platform = normalized;
478
- }
479
-
480
- // Optional caller-supplied absolute path. When present, the relay reads
481
- // the file directly and skips the legacy glob — the SDK has already
482
- // chosen the path under the BS session root. Shape errors (non-string,
483
- // non-absolute, too long) are 400. Existence and session-root scoping
484
- // are enforced by the shared realpath + prefix check below, which
485
- // returns 404 — same shape as the glob path. Treat empty string as
486
- // absent so older SDKs that emit the field unconditionally still fall
487
- // through to the glob.
488
- let suppliedFilePath = null;
489
- if (req.body.filePath !== undefined && req.body.filePath !== null && req.body.filePath !== '') {
490
- if (typeof req.body.filePath !== 'string') {
491
- throw new ServerError(400, 'Invalid filePath: must be a string');
492
- }
493
- if (req.body.filePath.length > 1024) {
494
- throw new ServerError(400, 'Invalid filePath: exceeds maximum length of 1024');
495
- }
496
- if (!path.isAbsolute(req.body.filePath)) {
497
- throw new ServerError(400, 'Invalid filePath: must be an absolute path');
498
- }
499
- suppliedFilePath = req.body.filePath;
500
- }
501
-
502
- // Resolve the file-find scope root. On BrowserStack (sessionId present),
503
- // the root is the BS host's /tmp/{sessionId}{_test_suite} convention.
504
- // Self-hosted (sessionId absent) requires PERCY_MAESTRO_SCREENSHOT_DIR
505
- // (read from process.env, never the request body) to be an absolute,
506
- // existing directory — typically the customer's
507
- // `maestro test --test-output-dir <DIR>` path. The realpath + prefix
508
- // check below enforces the security invariant at whichever root applies;
509
- // the boundary is relocated, not removed.
510
- let scopeRoot;
511
- if (selfHosted) {
512
- // Reject filePath outright in self-hosted mode. The SDK never emits
513
- // it (it sends a relative SCREENSHOT_NAME); honoring an absolute
514
- // filePath against a caller-influenceable root would re-open
515
- // arbitrary in-root reads.
516
- if (suppliedFilePath) {
517
- 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)');
518
- }
519
- let dir = process.env.PERCY_MAESTRO_SCREENSHOT_DIR;
520
- if (!dir) {
521
- throw new ServerError(400, 'Missing required env: PERCY_MAESTRO_SCREENSHOT_DIR (set it to your `maestro test --test-output-dir` path)');
522
- }
523
- if (!path.isAbsolute(dir)) {
524
- throw new ServerError(400, 'PERCY_MAESTRO_SCREENSHOT_DIR must be an absolute path');
525
- }
526
- // UX guard ONLY: surface an actionable 400 ("dir not found") instead
527
- // of the opaque 404 the realpath+prefix containment check below would
528
- // emit for a missing dir. There is a small TOCTOU window between this
529
- // stat and the realpath at line 647 — that window is acceptable here
530
- // because realpath (not stat) is the security invariant: even if the
531
- // dir is replaced with a symlink in between, realpath resolves the
532
- // target and the sep-prefix check rejects anything outside scopeRoot.
533
- let stat;
534
- try {
535
- stat = await fs.promises.stat(dir);
536
- } catch {
537
- stat = null;
538
- }
539
- if (!stat || !stat.isDirectory()) {
540
- throw new ServerError(400, `PERCY_MAESTRO_SCREENSHOT_DIR is not an existing directory: ${dir}`);
541
- }
542
- scopeRoot = dir;
543
- } else {
544
- scopeRoot = platform === 'ios' ? `/tmp/${sessionId}` : `/tmp/${sessionId}_test_suite`;
545
- }
546
-
547
- // Validate regions input shape early (before file I/O and ADB work) so
548
- // malformed requests don't consume resolver/relay work. Three parallel
549
- // input arrays share the same per-item shape; algorithm semantics differ
550
- // per array (regions only — ignoreRegions/considerRegions are implicit).
551
- const REGION_INPUT_FIELDS = ['regions', 'ignoreRegions', 'considerRegions'];
552
- for (let fieldName of REGION_INPUT_FIELDS) {
553
- let input = req.body[fieldName];
554
- if (input === undefined) continue;
555
- if (!Array.isArray(input)) {
556
- throw new ServerError(400, `${fieldName} must be an array`);
557
- }
558
- if (input.length > 50) {
559
- throw new ServerError(400, `${fieldName} exceeds maximum of 50`);
560
- }
561
- for (let [idx, region] of input.entries()) {
562
- if (region && region.element !== undefined) {
563
- if (typeof region.element !== 'object' || region.element === null || Array.isArray(region.element)) {
564
- throw new ServerError(400, `${fieldName}[${idx}].element must be an object`);
565
- }
566
- let keys = Object.keys(region.element);
567
- if (keys.length !== 1) {
568
- throw new ServerError(400, `${fieldName}[${idx}].element must have exactly one selector key`);
569
- }
570
- let [key] = keys;
571
- if (!SELECTOR_KEYS_WHITELIST.includes(key)) {
572
- throw new ServerError(400, `${fieldName}[${idx}].element: unsupported selector key "${key}" (allowed: ${SELECTOR_KEYS_WHITELIST.join(', ')})`);
573
- }
574
- let value = region.element[key];
575
- if (typeof value !== 'string' || value.length === 0) {
576
- throw new ServerError(400, `${fieldName}[${idx}].element.${key} must be a non-empty string`);
577
- }
578
- if (value.length > 512) {
579
- throw new ServerError(400, `${fieldName}[${idx}].element.${key} exceeds maximum length of 512`);
580
- }
581
- }
582
- }
583
- }
584
-
585
- // Locate the screenshot on disk. Two paths converge on `chosenFile`:
586
- // 1. `filePath` supplied (new SDK ≥ v0.4 — the SDK chose an absolute
587
- // path under the BS session root and saved Maestro's PNG there).
588
- // 2. Legacy glob (older SDKs — file lives at the BS-infra-chosen
589
- // SCREENSHOTS_DIR layout). Either way, the shared realpath +
590
- // session-root prefix check below enforces the security invariant.
591
- let chosenFile;
592
- if (suppliedFilePath) {
593
- chosenFile = suppliedFilePath;
594
- } else {
595
- // Legacy glob. Pattern depends on platform:
596
- // Android (BrowserStack mobile): /tmp/{sid}_test_suite/logs/*/screenshots/{name}.png
597
- // iOS (BrowserStack realmobile): /tmp/{sid}/<maestro_debug_dir>/**/{name}.png
598
- // realmobile builds SCREENSHOTS_DIR with literal slashes from the flow-path
599
- // concatenation, causing Maestro to mkdir a deeply nested structure under the
600
- // {device}_maestro_debug_ root. The `**` recursive match handles any depth.
601
- // Exact {name}.png match at the leaf filters out Maestro's emoji-prefixed
602
- // debug frames (e.g., `screenshot-❌-<timestamp>-(flow).png`).
603
- let searchPattern;
604
- if (selfHosted) {
605
- // Self-hosted: recursive glob under the customer's --test-output-dir
606
- // (PERCY_MAESTRO_SCREENSHOT_DIR). Recursive depth handles arbitrary
607
- // Maestro layouts; `name` is SAFE_ID-validated above so it cannot
608
- // contain separators or traversal characters.
609
- //
610
- // fast-glob requires forward-slashes in patterns on every platform
611
- // (per its docs: "Always use forward-slashes in glob expressions").
612
- // On Windows the scopeRoot from path.resolve contains backslashes,
613
- // so we normalize before embedding into the pattern. Production-
614
- // code Windows portability — verified by the CI Windows runner.
615
- const globRoot = scopeRoot.replace(/\\/g, '/');
616
- searchPattern = `${globRoot}/**/${name}.png`;
617
- } else {
618
- searchPattern = platform === 'ios' ? `/tmp/${sessionId}/*_maestro_debug_*/**/${name}.png` : `/tmp/${sessionId}_test_suite/logs/*/screenshots/${name}.png`;
619
- }
620
- let files;
621
- try {
622
- let {
623
- default: glob
624
- } = await import('fast-glob');
625
- // Self-hosted needs `dot: true` because Maestro's default output
626
- // directory is `.maestro/` — a dot-prefixed entry that fast-glob
627
- // hides by default. BS layouts have no dot-prefixed segments, so
628
- // omitting the option there keeps the byte-identical behavior.
629
- files = await glob(searchPattern, selfHosted ? {
630
- dot: true
631
- } : undefined);
632
- } catch {
633
- // Fast-glob import / glob call failed — fall back to manual walker.
634
- // See manualScreenshotWalk() at file top for the rationale + the
635
- // file-level .semgrepignore covering path-traversal sinks inside.
636
- // Self-hosted has no walker fallback (no fixed-layout convention) —
637
- // empty files → 404 with the actionable PERCY_MAESTRO_SCREENSHOT_DIR
638
- // guidance above.
639
- /* istanbul ignore next — only fires when fast-glob import throws
640
- (broken install / FS corruption); integration-test territory. */
641
- files = selfHosted ? [] : await manualScreenshotWalk(platform, sessionId, name);
642
- }
643
- if (!files || files.length === 0) {
644
- throw new ServerError(404, `Screenshot not found: ${name}.png (searched ${searchPattern})`);
645
- }
646
-
647
- // If multiple files match (iOS — same name reused across flows), pick the most recently modified
648
- // for determinism. The else branch only fires when a snapshot name
649
- // is reused across two flows in the same session; the realmobile
650
- // layout normally writes one file per snapshot per session, so the
651
- // multi-match path is exercised by integration tests on BS hosts
652
- // rather than the unit suite.
653
- /* istanbul ignore else */
654
- if (files.length === 1) {
655
- chosenFile = files[0];
656
- } else {
657
- let mtimes = await Promise.all(files.map(async f => {
658
- try {
659
- return {
660
- f,
661
- mtime: (await fs.promises.stat(f)).mtimeMs
662
- };
663
- } catch {
664
- return {
665
- f,
666
- mtime: 0
667
- };
668
- }
669
- }));
670
- mtimes.sort((a, b) => b.mtime - a.mtime);
671
- chosenFile = mtimes[0].f;
672
- }
673
- }
674
-
675
- // Canonicalize and confirm the resolved path still lives under scopeRoot.
676
- // Defeats symlink swaps where the root points elsewhere. Both ends are
677
- // realpath'd because /tmp is a symlink on macOS (where iOS hosts run).
678
- // The trailing `/` on the prefix is load-bearing — it prevents
679
- // sibling-prefix bypass (e.g. /x/.maestro vs /x/.maestro-secrets).
680
- //
681
- // Normalize both sides to forward-slashes before the prefix check so
682
- // the same code works on Windows (real-fs returns backslashes) AND on
683
- // POSIX (no-op) AND on memfs in tests (POSIX-style virtual paths
684
- // regardless of host OS).
685
- let realPath, realPrefix;
686
- try {
687
- realPath = await fs.promises.realpath(chosenFile);
688
- realPrefix = await fs.promises.realpath(scopeRoot);
689
- } catch {
690
- throw new ServerError(404, `Screenshot not found: ${name}.png (path resolution failed)`);
691
- }
692
- const realPathFwd = realPath.replace(/\\/g, '/');
693
- const realPrefixFwd = realPrefix.replace(/\\/g, '/');
694
- if (!realPathFwd.startsWith(`${realPrefixFwd}/`)) {
695
- throw new ServerError(404, `Screenshot not found: ${name}.png (resolved outside ${selfHosted ? 'PERCY_MAESTRO_SCREENSHOT_DIR' : 'session dir'})`);
696
- }
697
-
698
- // Read and base64-encode the screenshot
699
- let fileContent = await fs.promises.readFile(realPath);
700
- let base64Content = fileContent.toString('base64');
701
-
702
- // Parse the PNG header for actual rendered dimensions. The PNG bytes
703
- // ARE the source of truth — what Percy stores and compares against.
704
- // Fills tag.width/height when the customer didn't supply them (or
705
- // supplied invalid values); customer-supplied values continue to win
706
- // for backward compat with any flow that pins a specific tag dim.
707
- let pngDims = parsePngDimensions(fileContent);
708
-
709
- // Build tag from optional request body fields
710
- let tag = req.body.tag || {
711
- name: 'Unknown Device',
712
- osName: 'Android'
713
- };
714
- /* istanbul ignore if — fallback when tag.name is missing; tests always
715
- pass a complete tag object. */
716
- if (!tag.name) tag.name = 'Unknown Device';
717
- if (pngDims) {
718
- if (typeof tag.width !== 'number' || tag.width <= 0 || isNaN(tag.width)) {
719
- tag.width = pngDims.width;
720
- }
721
- if (typeof tag.height !== 'number' || tag.height <= 0 || isNaN(tag.height)) {
722
- tag.height = pngDims.height;
723
- }
724
- }
725
-
726
- // Construct comparison payload with tile metadata from request
727
- let payload = {
728
- name,
729
- tag,
730
- tiles: [{
731
- content: base64Content,
732
- statusBarHeight: req.body.statusBarHeight || 0,
733
- navBarHeight: req.body.navBarHeight || 0,
734
- headerHeight: 0,
735
- footerHeight: 0,
736
- fullscreen: req.body.fullscreen || false
737
- }],
738
- clientInfo: req.body.clientInfo || 'percy-maestro/0.1.0',
739
- environmentInfo: req.body.environmentInfo || 'percy-maestro'
740
- };
741
- if (req.body.testCase) payload.testCase = req.body.testCase;
742
- if (req.body.labels) payload.labels = req.body.labels;
743
- if (req.body.thTestCaseExecutionId) payload.thTestCaseExecutionId = req.body.thTestCaseExecutionId;
744
-
745
- // ───────────────────────────────────────────────────────────────────
746
- // REGIONS — end-to-end architecture
747
- // ───────────────────────────────────────────────────────────────────
748
- //
749
- // Regions tell Percy's diff engine which parts of a mobile screenshot
750
- // to ignore / consider / layout-compare. Two ways to specify one:
751
- //
752
- // 1. Coordinate region — caller already knows the pixel rectangle.
753
- // Shape: { top, left, right, bottom }. Forwarded as-is after
754
- // transform to `{x, y, width, height}` boundingBox.
755
- //
756
- // 2. Element region — caller knows a selector (`resource-id`, `text`,
757
- // `content-desc`, `class`, `id`) but not the on-screen bounds.
758
- // Resolved at relay-time against the live device's view hierarchy.
759
- //
760
- // ── Data flow (element region case) ────────────────────────────────
761
- //
762
- // SDK (percy-screenshot.js)
763
- // │ POST /percy/maestro-screenshot
764
- // │ { name, sessionId, platform, regions:[{element:{...}}], ... }
765
- // ▼
766
- // Relay (this handler)
767
- // │ validate selector shape (SELECTOR_KEYS_WHITELIST)
768
- // │ maestroDump({ platform, sessionId, grpcClientCache }) ← lazy + memoized per request
769
- // │ │
770
- // │ ├─ Android cascade (maestro-hierarchy.js)
771
- // │ │ gRPC primary → maestro-CLI → adb uiautomator
772
- // │ │ Three-class taxonomy: schema-class (drift bit, no
773
- // │ │ fallback) / channel-broken (evict cache, fall back) /
774
- // │ │ contention-class (keep cache, skip CLI → adb).
775
- // │ │
776
- // │ └─ iOS cascade
777
- // │ HTTP primary (Maestro XCTestRunner /viewHierarchy)
778
- // │ → maestro-CLI shell-out. AUT-root detection skips
779
- // │ SpringBoard frames.
780
- // │
781
- // │ firstMatch(nodes, selector) → bbox or null (warn-skip).
782
- // │ payload.regions[i].elementSelector.boundingBox = bbox
783
- // ▼
784
- // Percy backend — compares masked regions across builds.
785
- //
786
- // ── Observability ──────────────────────────────────────────────────
787
- //
788
- // /percy/healthcheck exposes maestroHierarchyDrift per platform:
789
- // { lastFailureClass, fallbackCount, succeededVia, code?, reason?, firstSeenAt? }
790
- // Every primary→fallback transition also emits one info-level line:
791
- // [percy] hierarchy: <primary> failed (<class>: <reason>) → falling back to <next>
792
- //
793
- // ── Failure shape ──────────────────────────────────────────────────
794
- //
795
- // Element regions degrade gracefully: resolver failure → warn-skip
796
- // those regions only; the snapshot itself still uploads. Coordinate
797
- // regions don't depend on the resolver and always pass through.
798
- //
799
- // ───────────────────────────────────────────────────────────────────
800
- // Shared resolver state across regions/ignoreRegions/considerRegions —
801
- // one hierarchy dump per request, one warn-once skip notice.
802
- let cachedDump = null;
803
- let elementSkipWarned = false;
804
- const totalElementRegionCount = REGION_INPUT_FIELDS.reduce((sum, f) => {
805
- let arr = req.body[f];
806
- return sum + (Array.isArray(arr) ? arr.filter(r => r && r.element).length : 0);
807
- }, 0);
808
-
809
- // Resolve one region input to {x, y, width, height}, or null when the
810
- // region is invalid or the resolver couldn't match it. Mutates the
811
- // shared cachedDump / warn-flag state above.
812
- async function resolveBbox(region) {
813
- if (region.top != null && region.bottom != null && region.left != null && region.right != null) {
814
- return {
815
- x: region.left,
816
- y: region.top,
817
- width: region.right - region.left,
818
- height: region.bottom - region.top
819
- };
820
- }
821
- /* istanbul ignore else — region.element false branch falls through
822
- to the istanbul-ignored "Invalid region format" warn below. */
823
- if (region.element) {
824
- /* istanbul ignore else — cachedDump === null only on first
825
- element-region per request; subsequent regions hit the cache. */
826
- if (cachedDump === null) {
827
- // Thread the per-Percy gRPC client cache so the Android gRPC
828
- // primary path can reuse channels across snapshots in the same
829
- // session (D9 of 2026-05-07-002 plan). iOS path ignores it
830
- // (the iOS resolver reads PERCY_IOS_DRIVER_HOST_PORT directly;
831
- // no per-session port cache needed since the port is prescribed
832
- // upstream by `@percy/cli-app`'s `maybeInjectDriverHostPort`).
833
- cachedDump = await maestroDump({
834
- platform,
835
- sessionId,
836
- grpcClientCache: percy.grpcClientCache
837
- });
838
- }
839
- /* istanbul ignore else — branch where dump resolves to hierarchy is
840
- happy-path element-region territory, integration-tested only. */
841
- if (cachedDump.kind !== 'hierarchy') {
842
- /* istanbul ignore else — elementSkipWarned latches after first
843
- warn; second+ iterations take the no-op branch. */
844
- if (!elementSkipWarned) {
845
- percy.log.warn(`Element-region resolver ${cachedDump.kind} (${cachedDump.reason}) — skipping ${totalElementRegionCount} element regions`);
846
- elementSkipWarned = true;
847
- }
848
- return null;
849
- }
850
- /* istanbul ignore next */
851
- let bbox = maestroFirstMatch(cachedDump.nodes, region.element);
852
- /* istanbul ignore next */
853
- if (!bbox) {
854
- percy.log.warn(`Element region not found: ${JSON.stringify(region.element)} — skipping`);
855
- return null;
856
- }
857
- /* istanbul ignore next — element-region happy path requires a
858
- non-stub maestroDump returning hierarchy nodes; unit tests run
859
- with stubbed resolver (env-missing), happy path covered by the
860
- cross-platform-parity integration harness against fixture data. */
861
- return bbox;
862
- }
863
- /* istanbul ignore next */
864
- percy.log.warn('Invalid region format, skipping');
865
- /* istanbul ignore next — region shape is validated upstream by the
866
- SDK before posting; this is a defensive catch-all for regions that
867
- lack both coordinate fields AND an element selector. */
868
- return null;
869
- }
870
-
871
- // regions[]: comparison-shape items with algorithm. Default algorithm is
872
- // 'ignore' (back-compat with SDK ≤ 0.3).
873
- if (Array.isArray(req.body.regions)) {
874
- let resolvedRegions = [];
875
- for (let region of req.body.regions) {
876
- let bbox = await resolveBbox(region);
877
- if (!bbox) continue;
878
- let resolved = {
879
- elementSelector: {
880
- boundingBox: bbox
881
- },
882
- algorithm: region.algorithm || 'ignore'
883
- };
884
- /* istanbul ignore if — region.configuration optional field; only
885
- passed when SDK opts in to per-region config overrides. */
886
- if (region.configuration) resolved.configuration = region.configuration;
887
- /* istanbul ignore if — region.padding optional field. */
888
- if (region.padding) resolved.padding = region.padding;
889
- /* istanbul ignore if — region.assertion optional field. */
890
- if (region.assertion) resolved.assertion = region.assertion;
891
- resolvedRegions.push(resolved);
892
- }
893
- /* istanbul ignore else — empty resolvedRegions branch only fires when
894
- ALL regions failed to resolve; happy path resolves at least one. */
895
- if (resolvedRegions.length > 0) payload.regions = resolvedRegions;
896
- }
897
-
898
- // ignoreRegions[] and considerRegions[]: parallel top-level payload
899
- // fields. Each item is shaped per regionsSchema (config.js:792) —
900
- // { coOrdinates: {top, left, bottom, right} } with an optional selector
901
- // hint preserved when the caller supplied an element selector.
902
- const REGION_OUTPUT_MAP = {
903
- ignoreRegions: {
904
- payloadKey: 'ignoredElementsData',
905
- innerKey: 'ignoreElementsData'
906
- },
907
- considerRegions: {
908
- payloadKey: 'consideredElementsData',
909
- innerKey: 'considerElementsData'
910
- }
911
- };
912
- for (let [inputField, {
913
- payloadKey,
914
- innerKey
915
- }] of Object.entries(REGION_OUTPUT_MAP)) {
916
- let input = req.body[inputField];
917
- if (!Array.isArray(input)) continue;
918
- let resolved = [];
919
- for (let region of input) {
920
- let bbox = await resolveBbox(region);
921
- /* istanbul ignore if — null bbox skip in ignoreRegions/considerRegions
922
- loop; tests cover the happy path where every region resolves. */
923
- if (!bbox) continue;
924
- let item = {
925
- coOrdinates: {
926
- top: bbox.y,
927
- left: bbox.x,
928
- bottom: bbox.y + bbox.height,
929
- right: bbox.x + bbox.width
930
- }
931
- };
932
- /* istanbul ignore if — element selector echo on resolved region;
933
- only fires when resolveBbox returned a bbox for an element region,
934
- which itself is integration-test territory (see resolveBbox
935
- above for the resolver-mock rationale). */
936
- if (region.element) {
937
- let [key] = Object.keys(region.element);
938
- item.selector = `${key}=${region.element[key]}`;
939
- }
940
- resolved.push(item);
941
- }
942
- /* istanbul ignore else — empty resolved branch only fires when ALL
943
- regions in this category failed to resolve; happy path resolves
944
- at least one. */
945
- if (resolved.length > 0) payload[payloadKey] = {
946
- [innerKey]: resolved
947
- };
948
- }
949
-
950
- // Upload via percy — sync or fire-and-forget
951
- if (req.body.sync === true) payload.sync = true;
952
- let data;
953
- if (percy.syncMode(payload)) {
954
- // See the /percy/comparison route: percy.upload() is the Promise-wrapped method;
955
- // calling it drives the generator and the sync queue resolves/rejects the callback.
956
- // The .catch(reject) surfaces generator errors that bypass that callback.
957
- const snapshotPromise = new Promise((resolve, reject) => {
958
- percy.upload(payload, {
959
- resolve,
960
- reject
961
- }, 'app').catch(reject);
962
- });
963
- data = await handleSyncJob(snapshotPromise, percy, 'comparison');
964
- return res.json(200, {
965
- success: true,
966
- data
967
- });
968
- }
969
- let upload = percy.upload(payload, null, 'app');
970
- /* istanbul ignore if — ?await=true URL flag triggers fire-and-wait;
971
- tests cover both syncMode and fire-and-forget but not the explicit
972
- ?await query-param variant. */
973
- if (req.url.searchParams.has('await')) await upload;
974
-
975
- // Generate redirect link
976
- let link = [percy.client.apiUrl, '/comparisons/redirect?', encodeURLSearchParams(normalize({
977
- buildId: (_percy$build3 = percy.build) === null || _percy$build3 === void 0 ? void 0 : _percy$build3.id,
978
- snapshot: {
979
- name
980
- },
981
- tag
982
- }, {
983
- snake: true
984
- }))].join('');
985
- return res.json(200, {
986
- success: true,
987
- link
988
- });
989
- })
300
+ .route('post', '/percy/maestro-screenshot', (req, res) => handleMaestroScreenshot(req, res, percy))
990
301
  // flushes one or more snapshots from the internal queue
991
302
  .route('post', '/percy/flush', async (req, res) => res.json(200, {
992
303
  success: await percy.flush(req.body).then(() => true)
@@ -1015,9 +326,9 @@ export function createPercyServer(percy, port) {
1015
326
  })
1016
327
  // Receives events from sdk's.
1017
328
  .route('post', '/percy/events', async (req, res) => {
1018
- var _percy$build4;
329
+ var _percy$build2;
1019
330
  const body = percyBuildEventHandler(req, pkg.version);
1020
- await percy.client.sendBuildEvents((_percy$build4 = percy.build) === null || _percy$build4 === void 0 ? void 0 : _percy$build4.id, body);
331
+ await percy.client.sendBuildEvents((_percy$build2 = percy.build) === null || _percy$build2 === void 0 ? void 0 : _percy$build2.id, body);
1021
332
  res.json(200, {
1022
333
  success: true
1023
334
  });
@@ -1037,8 +348,10 @@ export function createPercyServer(percy, port) {
1037
348
  success: true
1038
349
  });
1039
350
  })
1040
- // stops percy at the end of the current event loop
1041
- .route('/percy/stop', (req, res) => {
351
+ // stops percy at the end of the current event loop; POST-only so a browser
352
+ // cannot trigger it via a no-Origin GET (e.g. an <img> tag). Cross-origin
353
+ // POSTs are blocked by the general middleware's single choke point above.
354
+ .route('post', '/percy/stop', (req, res) => {
1042
355
  setImmediate(() => percy.stop());
1043
356
  return res.json(200, {
1044
357
  success: true