@percy/core 1.32.4-beta.0 → 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/network.js CHANGED
@@ -1,7 +1,8 @@
1
1
  import { request as makeRequest } from '@percy/client/utils';
2
2
  import logger from '@percy/logger';
3
3
  import mime from 'mime-types';
4
- import { AbortError, DefaultMap, createResource, hostnameMatches, normalizeURL, waitFor, decodeAndEncodeURLWithLogging, handleIncorrectFontMimeType, executeDomainValidation } from './utils.js';
4
+ import dns from 'dns';
5
+ import { AbortError, DefaultMap, createResource, hostnameMatches, normalizeURL, waitFor, decodeAndEncodeURLWithLogging, handleIncorrectFontMimeType, executeDomainValidation, isMetadataTarget, isMetadataIP } from './utils.js';
5
6
  export const MAX_RESOURCE_SIZE = 25 * 1024 ** 2 * 0.63; // 25MB, 0.63 factor for accounting for base64 encoding
6
7
  // CDP returns binary bodies via Network.getResponseBody as base64 in the JSON-RPC
7
8
  // response. Base64 inflates by 4/3, so an N-byte body becomes ~1.33×N on the wire.
@@ -36,6 +37,17 @@ export const AbortCodes = Object.freeze({
36
37
  TIMEOUT_NETWORK_IDLE: 'TIMEOUT_NETWORK_IDLE'
37
38
  });
38
39
 
40
+ // Thrown from the direct-fetch choke point (makeDirectRequest) when a Node-side
41
+ // fetch connects to a cloud metadata IP. Callers treat it as "already blocked
42
+ // and logged" and simply drop the resource without re-logging a network error.
43
+ export class MetadataBlockedError extends Error {
44
+ constructor(host) {
45
+ super(`Refusing to save direct-fetched resource from cloud metadata endpoint: ${host}`);
46
+ this.name = 'MetadataBlockedError';
47
+ this.host = host;
48
+ }
49
+ }
50
+
39
51
  // RequestLifeCycleHandler handles life cycle of a requestId
40
52
  // Ideal flow: requestWillBeSent -> requestPaused -> responseReceived -> loadingFinished / loadingFailed
41
53
  // ServiceWorker flow: requestWillBeSent -> responseReceived -> loadingFinished / loadingFailed
@@ -453,6 +465,31 @@ export class Network {
453
465
  /* istanbul ignore if: race condition paranoia */
454
466
  if (!request) return;
455
467
  request.response = response;
468
+
469
+ // DNS-rebinding-safe SSRF gate: block on the IP Chromium actually connected
470
+ // to (response.remoteIPAddress), before the body is ever buffered/uploaded.
471
+ // The request-time pre-check only inspects the literal host, so a hostname
472
+ // that resolves benignly at request time but rebinds to a metadata IP for
473
+ // the real connection slips past it and is caught here instead. Dropping the
474
+ // request now means _handleLoadingFinished finds nothing to save, so the
475
+ // metadata response body is never fetched via Network.getResponseBody.
476
+ let metadataHost = isMetadataIP(response.remoteIPAddress);
477
+ if (metadataHost) {
478
+ var _this$meta2;
479
+ let url = originURL(request);
480
+ logAssetInstrumentation(this.log, 'asset_not_uploaded', 'metadata_endpoint_blocked', {
481
+ url,
482
+ hostname: metadataHost,
483
+ snapshot: (_this$meta2 = this.meta) === null || _this$meta2 === void 0 ? void 0 : _this$meta2.snapshot
484
+ });
485
+ this.log.warn(`Refusing to capture resource from cloud metadata endpoint: ${metadataHost}`, {
486
+ ...this.meta,
487
+ url
488
+ });
489
+ this._forgetRequest(request);
490
+ this.#requestsLifeCycleHandler.get(requestId).resolveResponseReceived();
491
+ return;
492
+ }
456
493
  request.response.buffer = async () => {
457
494
  let result = await this.send(session, 'Network.getResponseBody', {
458
495
  requestId
@@ -595,6 +632,75 @@ export class Network {
595
632
  this.log.warn('Setting PERCY_NETWORK_IDLE_WAIT_TIMEOUT over 60000ms is not recommended. ' + 'If your page needs more than 60000ms to idle due to CPU/Network load, ' + 'its recommended to increase CI resources where this cli is running.');
596
633
  }
597
634
  }
635
+
636
+ // Perform the actual Node-side HTTP fetch for a request, attaching the page's
637
+ // cookies and (same-origin only) Basic auth. A custom dns `lookup` hook records
638
+ // the IP(s) the socket is actually resolving/connecting to — this is the same
639
+ // resolution Node uses for the connection (not an extra DNS round-trip), so the
640
+ // caller can enforce the SSRF metadata block on the real connected IP and defeat
641
+ // DNS rebinding on the direct-fetch path. Kept as an instance method so tests
642
+ // can stub the transport (and the connected IP) without hitting the network.
643
+ async directFetch(request, session) {
644
+ var _this$meta3;
645
+ let cookies = [];
646
+ let cookieSession = pickCookieSession(this, session);
647
+ try {
648
+ ({
649
+ cookies
650
+ } = await cookieSession.send('Network.getCookies', {
651
+ urls: [request.url]
652
+ }));
653
+ } catch (error) {
654
+ this.log.debug(`Network.getCookies unavailable for ${request.url}: ${error.message}`);
655
+ }
656
+ let headers = {
657
+ // add default browser
658
+ accept: '*/*',
659
+ 'sec-fetch-site': 'same-origin',
660
+ 'sec-fetch-mode': 'cors',
661
+ 'sec-fetch-dest': 'font',
662
+ 'sec-ch-ua': '"Chromium";v="143", "Google Chrome";v="143", "Not?A_Brand";v="99"',
663
+ 'sec-ch-ua-mobile': '?0',
664
+ 'sec-ch-ua-platform': '"macOS"',
665
+ 'sec-fetch-user': '?1',
666
+ // add request fetched headers
667
+ ...request.headers,
668
+ // add applicable cookies
669
+ cookie: cookies.map(cookie => `${cookie.name}=${cookie.value}`).join('; ')
670
+ };
671
+ if (shouldAttachAuth(this.authorization, request.url, (_this$meta3 = this.meta) === null || _this$meta3 === void 0 ? void 0 : _this$meta3.snapshotURL)) {
672
+ let {
673
+ username,
674
+ password
675
+ } = this.authorization;
676
+ let token = Buffer.from([username, password || ''].join(':')).toString('base64');
677
+ headers.Authorization = `Basic ${token}`;
678
+ }
679
+ let remoteAddresses = [];
680
+ let lookup = (hostname, opts, cb) => dns.lookup(hostname, opts, (err, address, family) => {
681
+ remoteAddresses.push(...flattenLookupAddresses(address));
682
+ cb(err, address, family);
683
+ });
684
+ let {
685
+ body,
686
+ status,
687
+ headers: responseHeaders
688
+ } = await makeRequest(request.url, {
689
+ buffer: true,
690
+ headers,
691
+ lookup
692
+ }, (body, res) => ({
693
+ body,
694
+ status: res.statusCode,
695
+ headers: res.headers
696
+ }));
697
+ return {
698
+ body,
699
+ status,
700
+ headers: responseHeaders,
701
+ remoteAddresses
702
+ };
703
+ }
598
704
  }
599
705
 
600
706
  // Logs asset instrumentation for failed/skipped asset loading
@@ -612,7 +718,8 @@ export function logAssetInstrumentation(log, category, reason, details) {
612
718
  resource_too_large: 'Resource too large',
613
719
  no_response: 'No response received',
614
720
  empty_response: 'Empty response',
615
- disallowed_resource_type: 'Disallowed resource type'
721
+ disallowed_resource_type: 'Disallowed resource type',
722
+ metadata_endpoint_blocked: 'Cloud metadata endpoint blocked'
616
723
  };
617
724
  const prefix = categoryMap[category];
618
725
  /* istanbul ignore next: fallback for unknown reason */
@@ -710,6 +817,7 @@ async function sendResponseResource(network, request, session) {
710
817
  let send = (method, params) => network.send(session, method, params);
711
818
  try {
712
819
  let resource = network.intercept.getResource(url, network.intercept.currentWidth);
820
+ let metadataHost;
713
821
  network.log.debug(`Handling request: ${url}`, meta);
714
822
  if (!(resource !== null && resource !== void 0 && resource.root) && hostnameMatches(disallowedHostnames, url)) {
715
823
  logAssetInstrumentation(log, 'asset_not_uploaded', 'disallowed_hostname', {
@@ -734,6 +842,30 @@ async function sendResponseResource(network, request, session) {
734
842
  value: String(v)
735
843
  }))
736
844
  });
845
+ } else if ((metadataHost = isMetadataTarget(url)) || request.redirectChain.length && (metadataHost = isMetadataTarget(request.url))) {
846
+ // Cheap, synchronous first-line block for SSRF pivots to cloud
847
+ // instance-metadata endpoints whose target is a literal metadata IP or a
848
+ // known metadata hostname — refused before issuing a real outbound
849
+ // request. This is a literal-only pre-check: it does NOT resolve DNS and
850
+ // therefore does NOT defend against DNS rebinding (a hostname that
851
+ // resolves benignly here can still connect to a metadata IP). The
852
+ // rebinding leg is closed at the response stage in _handleResponseReceived,
853
+ // which gates on response.remoteIPAddress — the IP actually connected to.
854
+ // Cache hits and root resources are served above and never reach here, so
855
+ // loopback/RFC1918 snapshotting is unaffected. We check both the origin
856
+ // URL and, on a redirect hop, the actual target (request.url) so an open
857
+ // redirect to a metadata endpoint cannot bypass the block — originURL
858
+ // reports the pre-redirect URL for resource identity.
859
+ logAssetInstrumentation(log, 'asset_not_uploaded', 'metadata_endpoint_blocked', {
860
+ url,
861
+ hostname: metadataHost,
862
+ snapshot: meta.snapshot
863
+ });
864
+ log.warn(`Refusing to fetch resource from cloud metadata endpoint: ${metadataHost}`, meta);
865
+ await send('Fetch.failRequest', {
866
+ requestId: request.interceptId,
867
+ errorReason: 'Aborted'
868
+ });
737
869
  } else {
738
870
  // interceptResponse:true triggers a second pause at the response stage. See _handleResponsePaused.
739
871
  await send('Fetch.continueRequest', {
@@ -811,53 +943,50 @@ export function resolveDirectFetchMime(responseHeaders, urlForLookup) {
811
943
  return serverMime || mime.lookup(urlForLookup) || 'application/octet-stream';
812
944
  }
813
945
 
814
- // Make a new request with Node based on a network request. Cookies are read
815
- // from the page session because worker/auxiliary sessions have a partial
816
- // Network domain where Network.getCookies throws "Internal error".
946
+ // Normalize the address argument passed to a dns.lookup callback into a flat
947
+ // array of IP strings. Node's http stack calls lookup with `all: true` (Happy
948
+ // Eyeballs), so `address` is an array of { address, family }; older/other
949
+ // callers may pass a single string. Missing values yield an empty list.
950
+ export function flattenLookupAddresses(address) {
951
+ if (Array.isArray(address)) return address.map(a => a.address);
952
+ return address ? [address] : [];
953
+ }
954
+
955
+ // The single choke point for all Node-side direct fetches (the direct-fetch
956
+ // fallback for worker scripts and the font-mime re-fetch in saveResponseResource).
957
+ // It runs the transport (network.directFetch) then enforces the SSRF metadata
958
+ // block on the IP(s) the socket actually connected to — the DNS-rebinding-safe
959
+ // equivalent of the response-stage remoteIPAddress gate, for requests that never
960
+ // surface a CDP response. On a hit it logs + warns and throws MetadataBlockedError
961
+ // so the caller drops the resource instead of buffering/uploading (or attaching
962
+ // cookies/auth to) a metadata response.
817
963
  async function makeDirectRequest(network, request, session) {
818
- var _network$meta;
819
- let cookies = [];
820
- let cookieSession = pickCookieSession(network, session);
821
- try {
822
- ({
823
- cookies
824
- } = await cookieSession.send('Network.getCookies', {
825
- urls: [request.url]
826
- }));
827
- } catch (error) {
828
- network.log.debug(`Network.getCookies unavailable for ${request.url}: ${error.message}`);
829
- }
830
- let headers = {
831
- // add default browser
832
- accept: '*/*',
833
- 'sec-fetch-site': 'same-origin',
834
- 'sec-fetch-mode': 'cors',
835
- 'sec-fetch-dest': 'font',
836
- 'sec-ch-ua': '"Chromium";v="143", "Google Chrome";v="143", "Not?A_Brand";v="99"',
837
- 'sec-ch-ua-mobile': '?0',
838
- 'sec-ch-ua-platform': '"macOS"',
839
- 'sec-fetch-user': '?1',
840
- // add request fetched headers
841
- ...request.headers,
842
- // add applicable cookies
843
- cookie: cookies.map(cookie => `${cookie.name}=${cookie.value}`).join('; ')
844
- };
845
- if (shouldAttachAuth(network.authorization, request.url, (_network$meta = network.meta) === null || _network$meta === void 0 ? void 0 : _network$meta.snapshotURL)) {
846
- let {
847
- username,
848
- password
849
- } = network.authorization;
850
- let token = Buffer.from([username, password || ''].join(':')).toString('base64');
851
- headers.Authorization = `Basic ${token}`;
964
+ let {
965
+ body,
966
+ status,
967
+ headers,
968
+ remoteAddresses
969
+ } = await network.directFetch(request, session);
970
+ let metadataHost = remoteAddresses.map(isMetadataIP).find(Boolean);
971
+ if (metadataHost) {
972
+ let url = originURL(request);
973
+ let meta = {
974
+ ...network.meta,
975
+ url
976
+ };
977
+ logAssetInstrumentation(network.log, 'asset_not_uploaded', 'metadata_endpoint_blocked', {
978
+ url,
979
+ hostname: metadataHost,
980
+ snapshot: meta.snapshot
981
+ });
982
+ network.log.warn(`Refusing to save direct-fetched resource from cloud metadata endpoint: ${metadataHost}`, meta);
983
+ throw new MetadataBlockedError(metadataHost);
852
984
  }
853
- return makeRequest(request.url, {
854
- buffer: true,
855
- headers
856
- }, (body, res) => ({
985
+ return {
857
986
  body,
858
- status: res.statusCode,
859
- headers: res.headers
860
- }));
987
+ status,
988
+ headers
989
+ };
861
990
  }
862
991
 
863
992
  // Capture a resource via direct HTTP fetch when the browser-side response
@@ -900,6 +1029,12 @@ async function captureResourceDirectly(network, request, session) {
900
1029
  log.debug(`- Saving direct-fetched resource sha=${resource.sha} mimetype=${mimeType}`, meta);
901
1030
  network.intercept.saveResource(resource);
902
1031
  } catch (error) {
1032
+ if (error instanceof MetadataBlockedError) {
1033
+ // The connected IP was a cloud metadata endpoint — makeDirectRequest has
1034
+ // already logged + warned. Drop the resource without re-logging it as a
1035
+ // generic network error so the metadata body is never saved/uploaded.
1036
+ return;
1037
+ }
903
1038
  logAssetInstrumentation(log, 'asset_load_missing', 'network_error', {
904
1039
  url,
905
1040
  snapshot: meta.snapshot,
package/dist/percy.js CHANGED
@@ -132,6 +132,15 @@ export class Percy {
132
132
  this.grpcClientCache = new Map();
133
133
  this.grpcClientCache.shutdownInProgress = false;
134
134
 
135
+ // Per-Percy cache of derived device system-bar insets, keyed by sessionId.
136
+ // Insets are device-constant within a session, so the Maestro relay derives
137
+ // them once (one /viewHierarchy or `dumpsys` call) and reuses the result —
138
+ // including a null "derivation failed, use SDK default" outcome — for every
139
+ // subsequent snapshot in that session. Per-instance (not module-scoped) so
140
+ // concurrent Percy instances don't share session state; holds plain data
141
+ // (no sockets), so stop() just clears it.
142
+ this.maestroInsetCache = new Map();
143
+
135
144
  // Domain validation state for auto domain allow-listing
136
145
  this.domainValidation = {
137
146
  autoConfiguredHosts: new Set(),
@@ -447,6 +456,9 @@ export class Percy {
447
456
  this.grpcClientCache.shutdownInProgress = true;
448
457
  closeGrpcClientCache(this.grpcClientCache);
449
458
 
459
+ // Drop the per-session device-inset cache (plain data, no sockets).
460
+ this.maestroInsetCache.clear();
461
+
450
462
  // mark instance as stopped
451
463
  this.readyState = 3;
452
464
  } catch (err) {
@@ -849,7 +861,10 @@ export class Percy {
849
861
  try {
850
862
  var _this$build5, _this$build6, _this$build7, _this$build8;
851
863
  const logsObject = {
852
- clilogs: logger.query(log => !['ci'].includes(log.debug))
864
+ // Redact secrets from CLI logs before egress to the Percy API — these
865
+ // can contain tokens or URLs with embedded credentials (CWE-532). The
866
+ // cilogs below were already redacted; clilogs were not.
867
+ clilogs: redactSecrets(logger.query(log => !['ci'].includes(log.debug)))
853
868
  };
854
869
 
855
870
  // Only add CI logs if not disabled voluntarily.
@@ -7021,4 +7021,8 @@ patterns:
7021
7021
  - pattern:
7022
7022
  name: Bitcoin Address
7023
7023
  regex: '^[13][a-km-zA-HJ-NP-Z0-9]{26,33}$'
7024
- confidence: high
7024
+ confidence: high
7025
+ - pattern:
7026
+ name: Percy Token
7027
+ regex: '\b(web|app|auto|ss|vmw|res)_[A-Za-z0-9]{20,}'
7028
+ confidence: high
package/dist/server.js CHANGED
@@ -11,6 +11,24 @@ import mime from 'mime-types';
11
11
  import disposition from 'content-disposition';
12
12
  import { pathToRegexp, match as pathToMatch, compile as makeToPath } from 'path-to-regexp';
13
13
 
14
+ // Returns true when an Origin header value resolves to a loopback host. The
15
+ // local Percy server is only ever legitimately reached by Node SDK clients
16
+ // (which send no Origin) or by loopback browser tooling (e.g. the Storybook
17
+ // manager on localhost:<port>). Treating non-loopback origins as untrusted lets
18
+ // us scope CORS and reject cross-origin state changes (CWE-942 / CWE-352).
19
+ export function isLoopbackOrigin(origin) {
20
+ if (!origin || typeof origin !== 'string') return false;
21
+ try {
22
+ // URL.hostname KEEPS the brackets around an IPv6 literal, so `[::1]`
23
+ // stays `[::1]` here and must be unwrapped before matching `::1`.
24
+ let host = new URL(origin).hostname.toLowerCase();
25
+ if (host.startsWith('[') && host.endsWith(']')) host = host.slice(1, -1);
26
+ return host === 'localhost' || host === '127.0.0.1' || host === '::1' || host.endsWith('.localhost');
27
+ } catch {
28
+ return false;
29
+ }
30
+ }
31
+
14
32
  // custom incoming message adds a `url` and `body` properties containing the parsed URL and message
15
33
  // buffer respectively; both available after the 'end' event is emitted
16
34
  export class IncomingMessage extends http.IncomingMessage {
@@ -116,15 +134,32 @@ export class Server extends http.Server {
116
134
  _classPrivateFieldInitSpec(this, _routes, [{
117
135
  priority: -1,
118
136
  handle: (req, res, next) => {
119
- res.setHeader('Access-Control-Allow-Origin', '*');
137
+ // Only echo a loopback Origin back as Access-Control-Allow-Origin. The
138
+ // previous wildcard `*` let any website the user visited read responses
139
+ // from the local Percy server (build data, config) cross-origin (CWE-942).
140
+ let origin = req.headers.origin;
141
+ let originAllowed = isLoopbackOrigin(origin);
142
+ // The response branches on Origin on every path (ACAO is emitted only for
143
+ // loopback origins), so Vary: Origin must be set unconditionally —
144
+ // otherwise a cache/intermediary could serve a no-ACAO body to a loopback
145
+ // origin, or a loopback body to another origin.
146
+ res.setHeader('Vary', 'Origin');
147
+ if (originAllowed) {
148
+ // `origin` is validated against a loopback-only allowlist above, so it
149
+ // is not attacker-controlled here.
150
+ // nosemgrep: javascript.express.security.cors-misconfiguration.cors-misconfiguration
151
+ res.setHeader('Access-Control-Allow-Origin', origin);
152
+ }
120
153
  if (req.method === 'OPTIONS') {
121
- let allowHeaders = req.headers['access-control-request-headers'] || '*';
122
- let allowMethods = [...new Set(_classPrivateFieldGet(_routes, this).flatMap(route => (!route.match || route.match(req.url.pathname)) && route.methods || []))].join(', ');
123
- res.setHeader('Access-Control-Allow-Headers', allowHeaders);
124
- res.setHeader('Access-Control-Allow-Methods', allowMethods);
154
+ if (originAllowed) {
155
+ let allowHeaders = req.headers['access-control-request-headers'] || '*';
156
+ let allowMethods = [...new Set(_classPrivateFieldGet(_routes, this).flatMap(route => (!route.match || route.match(req.url.pathname)) && route.methods || []))].join(', ');
157
+ res.setHeader('Access-Control-Allow-Headers', allowHeaders);
158
+ res.setHeader('Access-Control-Allow-Methods', allowMethods);
159
+ }
125
160
  res.writeHead(204).end();
126
161
  } else {
127
- res.setHeader('Access-Control-Expose-Headers', '*');
162
+ if (originAllowed) res.setHeader('Access-Control-Expose-Headers', '*');
128
163
  return next();
129
164
  }
130
165
  }
package/dist/snapshot.js CHANGED
@@ -38,6 +38,13 @@ function validateAndFixSnapshotUrl(snapshot) {
38
38
  // used to deserialize regular expression strings
39
39
  const RE_REGEXP = /^\/(.+)\/(\w+)?$/;
40
40
 
41
+ // Upper bound on the snapshot name length we will run user-controllable
42
+ // regex/glob matching against. A crafted, very long snapshot name reaching this
43
+ // matcher (e.g. via the local API) combined with a backtracking-prone pattern
44
+ // could otherwise trigger catastrophic backtracking / ReDoS (CWE-1333). Real
45
+ // snapshot names are short; an over-long name simply does not match patterns.
46
+ const MAX_MATCH_INPUT_LENGTH = 2048;
47
+
41
48
  // Returns true or false if a snapshot matches the provided include and exclude predicates. A
42
49
  // predicate can be an array of predicates, a regular expression, a glob pattern, or a function.
43
50
  function snapshotMatches(snapshot, include, exclude) {
@@ -48,14 +55,17 @@ function snapshotMatches(snapshot, include, exclude) {
48
55
  exclude
49
56
  } = include);
50
57
 
58
+ // guard pattern matching against pathologically long inputs (ReDoS)
59
+ let patternSafe = typeof snapshot.name === 'string' && snapshot.name.length <= MAX_MATCH_INPUT_LENGTH;
60
+
51
61
  // recursive predicate test function
52
62
  let test = (predicate, fallback) => {
53
63
  if (predicate && typeof predicate === 'string') {
54
- // snapshot name matches exactly or matches a glob
55
- let result = snapshot.name === predicate || micromatch.isMatch(snapshot.name, predicate);
64
+ // exact match is always safe; glob matching is only run on bounded input
65
+ let result = snapshot.name === predicate || patternSafe && micromatch.isMatch(snapshot.name, predicate);
56
66
 
57
- // snapshot might match a string-based regexp pattern
58
- if (!result) {
67
+ // snapshot might match a string-based regexp pattern (bounded input only)
68
+ if (!result && patternSafe) {
59
69
  try {
60
70
  let [, parsed, flags] = RE_REGEXP.exec(predicate) || [];
61
71
  result = !!parsed && new RegExp(parsed, flags).test(snapshot.name);
@@ -63,8 +73,8 @@ function snapshotMatches(snapshot, include, exclude) {
63
73
  }
64
74
  return result;
65
75
  } else if (predicate instanceof RegExp) {
66
- // snapshot matches a regular expression
67
- return predicate.test(snapshot.name);
76
+ // snapshot matches a regular expression (bounded input only)
77
+ return patternSafe && predicate.test(snapshot.name);
68
78
  } else if (typeof predicate === 'function') {
69
79
  // advanced matching
70
80
  return predicate(snapshot);
package/dist/unzip.js ADDED
@@ -0,0 +1,71 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import AdmZip from 'adm-zip';
4
+
5
+ // stat mode constants for entry external file attributes
6
+ const IFMT = 0o170000;
7
+ const IFDIR = 0o040000;
8
+ const IFLNK = 0o120000;
9
+
10
+ // Returns the file mode of an extracted entry, with defaults matching the
11
+ // previous extract-zip behavior when the archive does not provide one
12
+ function extractedMode(mode, isDir) {
13
+ return (mode || (isDir ? 0o755 : 0o644)) & 0o777;
14
+ }
15
+
16
+ // Extracts a zip archive into a directory, preserving file modes, directory
17
+ // entries, and symlinks. Replaces the unmaintained extract-zip package, whose
18
+ // yauzl@2 dependency deadlocks on deflate entries under Node 26
19
+ // (https://github.com/thejoshwolfe/yauzl/issues/176). adm-zip inflates
20
+ // synchronously so it is unaffected; its own extractAllTo is not used because
21
+ // it writes symlink entries as regular files, which breaks the Chromium.app
22
+ // bundle on macOS.
23
+ export default async function unzip(archive, {
24
+ dir
25
+ }) {
26
+ if (!path.isAbsolute(dir)) {
27
+ throw new Error('Target directory is expected to be absolute');
28
+ }
29
+ await fs.promises.mkdir(dir, {
30
+ recursive: true
31
+ });
32
+ dir = await fs.promises.realpath(dir);
33
+ for (let entry of new AdmZip(archive).getEntries()) {
34
+ // skip macOS resource fork entries
35
+ if (entry.entryName.startsWith('__MACOSX/')) continue;
36
+
37
+ // `dir` is the trusted install target from install.js, not user input,
38
+ // and entry names are validated by the traversal guard below
39
+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal
40
+ let dest = path.join(dir, entry.entryName);
41
+
42
+ // guard against zip-slip
43
+ if (path.relative(dir, dest).startsWith('..')) {
44
+ throw new Error(`Out of bound path "${dest}" found while processing file ${entry.entryName}`);
45
+ }
46
+ let mode = entry.header.attr >> 16 & 0xFFFF;
47
+ let isSymlink = (mode & IFMT) === IFLNK;
48
+ let isDir = (mode & IFMT) === IFDIR || entry.isDirectory ||
49
+ // directories from some windows archivers lack mode bits
50
+ entry.header.made >> 8 === 0 && entry.header.attr === 16;
51
+ if (isDir) {
52
+ await fs.promises.mkdir(dest, {
53
+ recursive: true,
54
+ mode: extractedMode(mode, true)
55
+ });
56
+ } else {
57
+ await fs.promises.mkdir(path.dirname(dest), {
58
+ recursive: true
59
+ });
60
+ // synchronous inflate with crc validation; throws on corrupted data
61
+ let contents = entry.getData();
62
+ if (isSymlink) {
63
+ await fs.promises.symlink(contents.toString('utf8'), dest);
64
+ } else {
65
+ await fs.promises.writeFile(dest, contents, {
66
+ mode: extractedMode(mode, false)
67
+ });
68
+ }
69
+ }
70
+ }
71
+ }