Welcome to mirror list, hosted at ThFree Co, Russian Federation.

sandbox.js « fixtures « test - github.com/npm/cli.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: b012790fb535d1464e20619fe2d76832f399e547 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
const { createHook, executionAsyncId } = require('async_hooks')
const { EventEmitter } = require('events')
const { homedir, tmpdir } = require('os')
const { dirname, join } = require('path')
const { promisify } = require('util')
const mkdirp = require('mkdirp-infer-owner')
const npmlog = require('npmlog')
const rimraf = promisify(require('rimraf'))

const chain = new Map()
const sandboxes = new Map()

// Disable lint errors for assigning to process global
/* global process:writable */

// keep a reference to the real process
const _process = process

createHook({
  init: (asyncId, type, triggerAsyncId, resource) => {
    // track parentage of asyncIds
    chain.set(asyncId, triggerAsyncId)
  },
  before: (asyncId) => {
    // find the nearest parent id that has a sandbox
    let parent = asyncId
    while (chain.has(parent) && !sandboxes.has(parent)) {
      parent = chain.get(parent)
    }

    process = sandboxes.has(parent)
      ? sandboxes.get(parent)
      : _process
  },
}).enable()

for (const level in npmlog.levels) {
  npmlog[`_${level}`] = npmlog[level]
  npmlog[level] = (...args) => {
    process._logs = process._logs || {}
    process._logs[level] = process._logs[level] || []
    process._logs[level].push(args)
    const _level = npmlog.level
    npmlog.level = 'silent'
    npmlog[`_${level}`](...args)
    npmlog.level = _level
  }
}

const _data = Symbol('sandbox.data')
const _dirs = Symbol('sandbox.dirs')
const _test = Symbol('sandbox.test')
const _mocks = Symbol('sandbox.mocks')
const _npm = Symbol('sandbox.npm')
const _parent = Symbol('sandbox.parent')
const _output = Symbol('sandbox.output')
const _proxy = Symbol('sandbox.proxy')
const _get = Symbol('sandbox.proxy.get')
const _set = Symbol('sandbox.proxy.set')

// these config keys can be redacted widely
const redactedDefaults = [
  'node-version',
  'npm-version',
  'tmp',
]

// we can't just replace these values everywhere because they're known to be
// very short strings that could be present all over the place, so we only
// replace them if they're located within quotes for now
const vagueRedactedDefaults = [
  'editor',
  'shell',
]

const normalize = (str) => str
  .replace(/\r\n/g, '\n') // normalize line endings (for ini)
  .replace(/[A-z]:\\/g, '\\') // turn windows roots to posix ones
  .replace(/\\+/g, '/') // replace \ with /

class Sandbox extends EventEmitter {
  constructor (test, options = {}) {
    super()

    this[_test] = test
    this[_mocks] = options.mocks || {}
    this[_data] = new Map()
    this[_output] = []
    const tempDir = `${test.testdirName}-sandbox`
    this[_dirs] = {
      temp: tempDir,
      global: options.global || join(tempDir, 'global'),
      home: options.home || join(tempDir, 'home'),
      project: options.project || join(tempDir, 'project'),
    }

    this[_proxy] = new Proxy(_process, {
      get: this[_get].bind(this),
      set: this[_set].bind(this),
    })
    this[_proxy].env = {}
    this[_proxy].argv = []

    test.cleanSnapshot = this.cleanSnapshot.bind(this)
    test.afterEach(() => this.reset())
    test.teardown(() => this.teardown())
  }

  get config () {
    return this[_npm] && this[_npm].config
  }

  get logs () {
    return this[_proxy]._logs
  }

  get global () {
    return this[_dirs].global
  }

  get home () {
    return this[_dirs].home
  }

  get project () {
    return this[_dirs].project
  }

  get process () {
    return this[_proxy]
  }

  get output () {
    return this[_output].map((line) => line.join(' ')).join('\n')
  }

  cleanSnapshot (snapshot) {
    let clean = normalize(snapshot)

    const viewer = _process.platform === 'win32'
      ? /"browser"([^:]+|$)/g
      : /"man"([^:]+|$)/g

    // the global prefix is platform dependent
    const realGlobalPrefix = _process.platform === 'win32'
      ? dirname(_process.execPath)
      : dirname(dirname(_process.execPath))

    const cache = _process.platform === 'win32'
      ? /\{HOME\}\/npm-cache(\r?\n|"|\/|$)/g
      : /\{HOME\}\/\.npm(\n|"|\/|$)/g

    // and finally replace some paths we know could be present
    clean = clean
      .replace(viewer, '"{VIEWER}"$1')
      .split(normalize(this[_proxy].execPath)).join('{EXECPATH}')
      .split(normalize(_process.execPath)).join('{REALEXECPATH}')
      .split(normalize(this.global)).join('{GLOBALPREFIX}')
      .split(normalize(realGlobalPrefix)).join('{REALGLOBALREFIX}')
      .split(normalize(this.project)).join('{LOCALPREFIX}')
      .split(normalize(this.home)).join('{HOME}')
      .replace(cache, '{CACHE}$1')
      .split(normalize(dirname(dirname(__dirname)))).join('{NPMDIR}')
      .split(normalize(tmpdir())).join('{TMP}')
      .split(normalize(homedir())).join('{REALHOME}')
      .split(this[_proxy].platform).join('{PLATFORM}')
      .split(this[_proxy].arch).join('{ARCH}')

    // We do the defaults after everything else so that they don't cause the
    // other cleaners to miss values we would have clobbered here.  For
    // instance if execPath is /home/user/.nvm/versions/node/1.0.0/bin/node,
    // and we replaced the node version first, the real execPath we're trying
    // to replace would no longer be represented, and be missed.
    if (this[_npm]) {
      // replace default config values with placeholders
      for (const name of redactedDefaults) {
        const value = this[_npm].config.defaults[name]
        clean = clean.split(value).join(`{${name.toUpperCase()}}`)
      }

      // replace vague default config values that are present within quotes
      // with placeholders
      for (const name of vagueRedactedDefaults) {
        const value = this[_npm].config.defaults[name]
        clean = clean.split(`"${value}"`).join(`"{${name.toUpperCase()}}"`)
      }
    }

    return clean
  }

  // test.afterEach hook
  reset () {
    this.removeAllListeners()
    this[_parent] = undefined
    this[_output] = []
    this[_data].clear()
    this[_proxy].env = {}
    this[_proxy].argv = []
    this[_npm] = undefined
  }

  // test.teardown hook
  teardown () {
    if (this[_parent]) {
      sandboxes.delete(this[_parent])
    }

    return rimraf(this[_dirs].temp).catch(() => null)
  }

  // proxy get handler
  [_get] (target, prop, receiver) {
    if (this[_data].has(prop)) {
      return this[_data].get(prop)
    }

    if (this[prop] !== undefined) {
      return Reflect.get(this, prop, this)
    }

    const actual = Reflect.get(target, prop, receiver)
    if (typeof actual === 'function') {
      // in node 10.1 there's an interesting bug where if a function on process
      // is called without explicitly forcing the 'this' arg to something, we
      // get 'Illegal invocation' errors. wrapping function properties in their
      // own proxy so that we can make sure the context is right fixes it
      return new Proxy(actual, {
        apply: (target, context, args) => {
          return Reflect.apply(target, _process, args)
        },
      })
    }

    return actual
  }

  // proxy set handler
  [_set] (target, prop, value) {
    if (prop === 'env') {
      value = {
        ...value,
        HOME: this.home,
      }
    }

    if (prop === 'argv') {
      value = [
        process.execPath,
        join(dirname(process.execPath), 'npm'),
        ...value,
      ]
    }

    return this[_data].set(prop, value)
  }

  async run (command, argv = []) {
    await Promise.all([
      mkdirp(this.project),
      mkdirp(this.home),
      mkdirp(this.global),
    ])

    // attach the sandbox process now, doing it after the promise above is
    // necessary to make sure that only async calls spawned as part of this
    // call to run will receive the sandbox. if we attach it too early, we
    // end up interfering with tap
    this[_parent] = executionAsyncId()
    this[_data].set('_asyncId', this[_parent])
    sandboxes.set(this[_parent], this[_proxy])
    process = this[_proxy]

    this[_proxy].argv = [
      '--prefix', this.project,
      '--userconfig', join(this.home, '.npmrc'),
      '--globalconfig', join(this.global, 'npmrc'),
      command,
      ...argv,
    ]

    const Npm = this[_test].mock('../../lib/npm.js', this[_mocks])
    this[_npm] = new Npm()
    this[_npm].output = (...args) => this[_output].push(args)
    await this[_npm].load()
    // in some node versions (later 10.x) our executionAsyncId at this point
    // will for some reason appear to have been triggered by a different parent
    // so immediately after load, if we can see that we lost our ancestry, we
    // fix it here with a hammer
    if (chain.get(executionAsyncId()) !== this[_parent]) {
      chain.set(executionAsyncId(), this[_parent])
      process = this[_proxy]
    }

    const cmd = this[_npm].argv.shift()
    return this[_npm].exec(cmd, this[_npm].argv)
  }

  async complete (command, argv, partial) {
    if (!Array.isArray(argv)) {
      partial = argv
      argv = []
    }

    await Promise.all([
      mkdirp(this.project),
      mkdirp(this.home),
      mkdirp(this.global),
    ])

    // attach the sandbox process now, doing it after the promise above is
    // necessary to make sure that only async calls spawned as part of this
    // call to run will receive the sandbox. if we attach it too early, we
    // end up interfering with tap
    this[_parent] = executionAsyncId()
    this[_data].set('_asyncId', this[_parent])
    sandboxes.set(this[_parent], this[_proxy])
    process = this[_proxy]

    this[_proxy].argv = [
      '--prefix', this.project,
      '--userconfig', join(this.home, '.npmrc'),
      '--globalconfig', join(this.global, 'npmrc'),
      command,
      ...argv,
    ]

    const Npm = this[_test].mock('../../lib/npm.js', this[_mocks])
    this[_npm] = new Npm()
    this[_npm].output = (...args) => this[_output].push(args)
    await this[_npm].load()
    // in some node versions (later 10.x) our executionAsyncId at this point
    // will for some reason appear to have been triggered by a different parent
    // so immediately after load, if we can see that we lost our ancestry, we
    // fix it here with a hammer
    if (chain.get(executionAsyncId()) !== this[_parent]) {
      chain.set(executionAsyncId(), this[_parent])
      process = this[_proxy]
    }

    const impl = await this[_npm].cmd(command)
    return impl.completion({
      partialWord: partial,
      conf: {
        argv: {
          remain: ['npm', command, ...argv],
        },
      },
    })
  }
}

module.exports = Sandbox