Skip to content
← Public packages

@kody/dropbox

Reusable Dropbox OAuth helpers for account, metadata, search, file transfer, sharing, and generic API requests.

FollowFork

Files

content-hash.test.ts

46 lines · 1.6 KB · TypeScript
import assert from 'node:assert/strict'
import { createHash, randomBytes } from 'node:crypto'
import { test } from 'node:test'
import {
	DROPBOX_CONTENT_HASH_BLOCK_BYTES,
	createDropboxContentHasher,
	dropboxContentHash,
} from '../src/content-hash.ts'

function reference(bytes: Uint8Array): string {
	const digests: Buffer[] = []
	for (let offset = 0; offset < bytes.byteLength; offset += DROPBOX_CONTENT_HASH_BLOCK_BYTES) {
		digests.push(
			createHash('sha256')
				.update(bytes.subarray(offset, offset + DROPBOX_CONTENT_HASH_BLOCK_BYTES))
				.digest(),
		)
	}
	return createHash('sha256').update(Buffer.concat(digests)).digest('hex')
}

test('empty input hashes to sha256 of nothing', async () => {
	assert.equal(
		await dropboxContentHash(new Uint8Array(0)),
		createHash('sha256').update(Buffer.alloc(0)).digest('hex'),
	)
})

test('matches the block algorithm across block boundaries', async () => {
	for (const size of [1, DROPBOX_CONTENT_HASH_BLOCK_BYTES, DROPBOX_CONTENT_HASH_BLOCK_BYTES + 1, 9 * 1024 * 1024 + 7]) {
		const bytes = new Uint8Array(randomBytes(size))
		assert.equal(await dropboxContentHash(bytes), reference(bytes), `size ${size}`)
	}
})

test('incremental hasher matches one-shot for uneven pieces', async () => {
	const bytes = new Uint8Array(randomBytes(11 * 1024 * 1024 + 3))
	const hasher = createDropboxContentHasher()
	for (let offset = 0; offset < bytes.byteLength; ) {
		const size = Math.min(1_234_567 + (offset % 3) * 3_000_000, bytes.byteLength - offset)
		await hasher.update(bytes.subarray(offset, offset + size))
		offset += size
	}
	assert.equal(hasher.byteLength, bytes.byteLength)
	assert.equal(await hasher.digest(), reference(bytes))
})