|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +const common = require('../common'); |
| 4 | +if (!common.hasCrypto) common.skip('missing crypto'); |
| 5 | + |
| 6 | +const tmpdir = require('../common/tmpdir'); |
| 7 | +const assert = require('assert'); |
| 8 | +const { spawnSync } = require('child_process'); |
| 9 | +const crypto = require('crypto'); |
| 10 | +const fs = require('fs'); |
| 11 | +const path = require('path'); |
| 12 | +const { pathToFileURL } = require('url'); |
| 13 | + |
| 14 | +tmpdir.refresh(); |
| 15 | + |
| 16 | +function hash(algo, body) { |
| 17 | + const h = crypto.createHash(algo); |
| 18 | + h.update(body); |
| 19 | + return h.digest('base64'); |
| 20 | +} |
| 21 | + |
| 22 | +const policyFilepath = path.join(tmpdir.path, 'policy'); |
| 23 | + |
| 24 | +const parentFilepath = path.join(tmpdir.path, 'parent.js'); |
| 25 | +const parentBody = "require('./dep.js')"; |
| 26 | + |
| 27 | +const depFilepath = path.join(tmpdir.path, 'dep.js'); |
| 28 | +const depURL = pathToFileURL(depFilepath); |
| 29 | +const depBody = ''; |
| 30 | + |
| 31 | +fs.writeFileSync(parentFilepath, parentBody); |
| 32 | +fs.writeFileSync(depFilepath, depBody); |
| 33 | + |
| 34 | +const tmpdirURL = pathToFileURL(tmpdir.path); |
| 35 | +if (!tmpdirURL.pathname.endsWith('/')) { |
| 36 | + tmpdirURL.pathname += '/'; |
| 37 | +} |
| 38 | + |
| 39 | +function test({ shouldFail, integrity }) { |
| 40 | + const resources = { |
| 41 | + [depURL]: { |
| 42 | + body: depBody, |
| 43 | + integrity |
| 44 | + } |
| 45 | + }; |
| 46 | + const manifest = { |
| 47 | + resources: {}, |
| 48 | + }; |
| 49 | + for (const [url, { body, integrity }] of Object.entries(resources)) { |
| 50 | + manifest.resources[url] = { |
| 51 | + integrity, |
| 52 | + }; |
| 53 | + fs.writeFileSync(new URL(url, tmpdirURL.href), body); |
| 54 | + } |
| 55 | + fs.writeFileSync(policyFilepath, JSON.stringify(manifest, null, 2)); |
| 56 | + const { status } = spawnSync(process.execPath, [ |
| 57 | + '--experimental-policy', |
| 58 | + policyFilepath, |
| 59 | + depFilepath |
| 60 | + ]); |
| 61 | + if (shouldFail) { |
| 62 | + assert.notStrictEqual(status, 0); |
| 63 | + } else { |
| 64 | + assert.strictEqual(status, 0); |
| 65 | + } |
| 66 | +} |
| 67 | + |
| 68 | +test({ |
| 69 | + shouldFail: false, |
| 70 | + integrity: `sha256-${hash('sha256', depBody)}`, |
| 71 | +}); |
| 72 | +test({ |
| 73 | + shouldFail: true, |
| 74 | + integrity: `1sha256-${hash('sha256', depBody)}`, |
| 75 | +}); |
| 76 | +test({ |
| 77 | + shouldFail: true, |
| 78 | + integrity: 'hoge', |
| 79 | +}); |
| 80 | +test({ |
| 81 | + shouldFail: true, |
| 82 | + integrity: `sha256-${hash('sha256', depBody)}sha256-${hash( |
| 83 | + 'sha256', |
| 84 | + depBody |
| 85 | + )}`, |
| 86 | +}); |
0 commit comments