Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add file hashes to asar header #221

Merged
merged 14 commits into from
Sep 9, 2021
Merged
Show file tree
Hide file tree
Changes from 10 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
21 changes: 18 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -153,12 +153,20 @@ Structure of `header` is something like this:
"ls": {
"offset": "0",
"size": 100,
"executable": true
"executable": true,
"integrity": {
"algorithm": "SHA256",
"hash": "..."
MarshallOfSound marked this conversation as resolved.
Show resolved Hide resolved
}
},
"cd": {
"offset": "100",
"size": 100,
"executable": true
"executable": true,
"integrity": {
"algorithm": "SHA256",
"hash": "..."
}
}
}
}
Expand All @@ -168,7 +176,11 @@ Structure of `header` is something like this:
"files": {
"hosts": {
"offset": "200",
"size": 32
"size": 32,
"integrity": {
"algorithm": "SHA256",
"hash": "..."
}
}
}
}
Expand All @@ -187,6 +199,9 @@ precisely represent UINT64 in JavaScript `Number`. `size` is a JavaScript
because file size in Node.js is represented as `Number` and it is not safe to
convert `Number` to UINT64.

`integrity` is an object consisting of a hashing `algorithm` and a hex encoded
`hash` value.
MarshallOfSound marked this conversation as resolved.
Show resolved Hide resolved

[pickle]: https://chromium.googlesource.com/chromium/src/+/master/base/pickle.h
[node-pickle]: https://www.npmjs.org/package/chromium-pickle
[grunt-asar]: https://github.com/bwin/grunt-asar
7 changes: 7 additions & 0 deletions lib/asar.js
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,10 @@ module.exports.statFile = function (archive, filename, followLinks) {
return filesystem.getFile(filename, followLinks)
}

module.exports.getRawHeader = function (archive) {
return disk.readArchiveHeaderSync(archive)
}

module.exports.listPackage = function (archive, options) {
return disk.readFilesystemSync(archive).listFiles(options)
}
Expand Down Expand Up @@ -199,6 +203,9 @@ module.exports.extractAll = function (archive, dest) {
// it's a file, extract it
const content = disk.readFileSync(filesystem, filename, file)
fs.writeFileSync(destFilename, content)
if (file.executable) {
fs.chmodSync(destFilename, '755')
}
MarshallOfSound marked this conversation as resolved.
Show resolved Hide resolved
}
}
}
Expand Down
14 changes: 12 additions & 2 deletions lib/crawlfs.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,22 +9,32 @@ async function determineFileType (filename) {
const stat = await fs.lstat(filename)
if (stat.isFile()) {
return { type: 'file', stat }
} else if (stat.isDirectory()) {
return { type: 'directory', stat }
} else if (stat.isSymbolicLink()) {
return { type: 'link', stat }
} else if (stat.isDirectory()) {
return { type: 'directory', stat }
MarshallOfSound marked this conversation as resolved.
Show resolved Hide resolved
}
}

module.exports = async function (dir, options) {
const metadata = {}
const crawled = await glob(dir, options)
const results = await Promise.all(crawled.map(async filename => [filename, await determineFileType(filename)]))
const links = []
const filenames = results.map(([filename, type]) => {
if (type) {
metadata[filename] = type
if (type.type === 'link') links.push(filename)
}
return filename
}).filter((filename) => {
// Newer glob can return files inside symlinked directories, to avoid
// those appearing in archives we need to manually exclude theme here
MarshallOfSound marked this conversation as resolved.
Show resolved Hide resolved
const exactLinkIndex = links.findIndex(link => filename === link)
return links.every((link, index) => {
if (index === exactLinkIndex) return true
return !filename.startsWith(link)
})
})
return [filenames, metadata]
}
Expand Down
2 changes: 1 addition & 1 deletion lib/disk.js
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ module.exports.readArchiveHeaderSync = function (archive) {

const headerPickle = pickle.createFromBuffer(headerBuf)
const header = headerPickle.createIterator().readString()
return { header: JSON.parse(header), headerSize: size }
return { headerString: header, header: JSON.parse(header), headerSize: size }
}

module.exports.readFilesystemSync = function (archive) {
Expand Down
3 changes: 3 additions & 0 deletions lib/filesystem.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ const os = require('os')
const path = require('path')
const { promisify } = require('util')
const stream = require('stream')
const getFileIntegrity = require('./integrity')

const UINT32_MAX = 2 ** 32 - 1

Expand Down Expand Up @@ -57,6 +58,7 @@ class Filesystem {
if (shouldUnpack || dirNode.unpacked) {
node.size = file.stat.size
node.unpacked = true
node.integrity = await getFileIntegrity(p)
return Promise.resolve()
}

Expand Down Expand Up @@ -86,6 +88,7 @@ class Filesystem {

node.size = size
node.offset = this.offset.toString()
node.integrity = await getFileIntegrity(p)
if (process.platform !== 'win32' && (file.stat.mode & 0o100)) {
node.executable = true
}
Expand Down
22 changes: 22 additions & 0 deletions lib/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,27 @@ export type InputMetadata = {
}
};

export type DirectoryRecord = {
files: Record<string, DirectoryRecord | FileRecord>;
};

export type FileRecord = {
offset: string;
size: number;
executable?: boolean;
integrity: {
hash: string;
algorithm: 'SHA256';
};
MarshallOfSound marked this conversation as resolved.
Show resolved Hide resolved
}

export type ArchiveHeader = {
// The JSON parsed header string
header: DirectoryRecord;
headerString: string;
headerSize: number;
}

export function createPackage(src: string, dest: string): Promise<void>;
export function createPackageWithOptions(
src: string,
Expand All @@ -59,6 +80,7 @@ export function createPackageFromFiles(
): Promise<void>;

export function statFile(archive: string, filename: string, followLinks?: boolean): Metadata;
export function getRawHeader(archive: string): ArchiveHeader;
export function listPackage(archive: string, options?: ListOptions): string[];
export function extractFile(archive: string, filename: string): Buffer;
export function extractAll(archive: string, dest: string): void;
Expand Down
62 changes: 62 additions & 0 deletions lib/integrity.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
const crypto = require('crypto')
const fs = require('fs')
const stream = require('stream')
const { promisify } = require('util')

const ALGORITHM = 'SHA256'
// 4MB default block size
const BLOCK_SIZE = 4 * 1024 * 1024

const pipeline = promisify(stream.pipeline)

async function getFileIntegrity (path) {
const read = fs.createReadStream(path)
const hash = crypto.createHash(ALGORITHM)
hash.setEncoding('hex')
await pipeline(
read,
hash
)

const blocks = []
let currentBlockSize = 0
let currentBlock = []

await pipeline(
fs.createReadStream(path),
new stream.PassThrough({
decodeStrings: false,
transform (_chunk, encoding, callback) {
function handleChunk (chunk) {
const diffToSlice = Math.min(BLOCK_SIZE - currentBlockSize, chunk.byteLength)
currentBlockSize += diffToSlice
currentBlock.push(chunk.slice(0, diffToSlice))
if (currentBlockSize === BLOCK_SIZE) {
blocks.push(Buffer.concat(currentBlock))
MarshallOfSound marked this conversation as resolved.
Show resolved Hide resolved
currentBlock = []
currentBlockSize = 0
}
if (diffToSlice < chunk.byteLength) {
handleChunk(chunk.slice(diffToSlice))
}
}
handleChunk(_chunk)
MarshallOfSound marked this conversation as resolved.
Show resolved Hide resolved
callback()
},
flush (callback) {
blocks.push(Buffer.concat(currentBlock))
currentBlock = []
callback()
}
})
)

return {
algorithm: ALGORITHM,
hash: hash.read(),
MarshallOfSound marked this conversation as resolved.
Show resolved Hide resolved
blockSize: BLOCK_SIZE,
blocks: blocks.map(block => crypto.createHash(ALGORITHM).update(block).digest('hex'))
}
}

module.exports = getFileIntegrity
Binary file modified test/expected/packthis-all-unpacked.asar
Binary file not shown.
Binary file modified test/expected/packthis-transformed.asar
Binary file not shown.
Binary file modified test/expected/packthis-unicode-path.asar
Binary file not shown.
Binary file modified test/expected/packthis-unpack-dir-glob.asar
Binary file not shown.
Binary file modified test/expected/packthis-unpack-dir-globstar.asar
Binary file not shown.
Binary file modified test/expected/packthis-unpack-dir.asar
Binary file not shown.
Binary file modified test/expected/packthis-unpack.asar
Binary file not shown.
Binary file modified test/expected/packthis-without-hidden.asar
Binary file not shown.
Binary file modified test/expected/packthis.asar
Binary file not shown.
3 changes: 3 additions & 0 deletions test/util/compareFiles.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ const assert = require('assert')
const fs = require('../../lib/wrapped-fs')

module.exports = async function (actualFilePath, expectedFilePath) {
if (process.env.ELECTRON_ASAR_SPEC_UPDATE) {
await fs.writeFile(expectedFilePath, await fs.readFile(actualFilePath))
}
const [actual, expected] = await Promise.all([fs.readFile(actualFilePath, 'utf8'), fs.readFile(expectedFilePath, 'utf8')])
assert.strictEqual(actual, expected)
}