// blob-serve: the shared-overlay blob helpers behind favela-web's com.atproto.sync.getBlob (slice 3b).
// Guards the load-bearing "one physical copy" invariant: roomKey16 MUST match hpp's on-disk dir derivation,
// or hpp and favela-web would write a DID's content to different directories and drift.
import test from 'node:test'
import assert from 'node:assert/strict'
import { roomKey16, blobPath, sniffMime, isSafeCid } from '../lib/blob-serve.js'
test('roomKey16 is deterministic and matches hpp on-disk dir for wj62', () => {
const wj62 = 'did:plc:wj62ebbusln6gxo5azo6ogzo'
// This exact value is hpp's on-disk namespace dir for wj62 — proven by inspecting the live overlay store.
assert.equal(roomKey16(wj62), '0d6d2249141a9549')
assert.equal(roomKey16(wj62), roomKey16(wj62)) // stable across calls
assert.notEqual(roomKey16(wj62), roomKey16('did:plc:someotherdidxxxxxxxxxxxx'))
assert.match(roomKey16(wj62), /^[0-9a-f]{16}$/)
})
test('blobPath composes root/<roomKey16>/blobs/<cid>', () => {
const did = 'did:plc:wj62ebbusln6gxo5azo6ogzo'
assert.equal(blobPath('/data/overlay', did, 'bafcid123'), '/data/overlay/0d6d2249141a9549/blobs/bafcid123')
})
test('sniffMime detects image formats from magic bytes, else octet-stream', () => {
const jpeg = Buffer.from([0xFF, 0xD8, 0xFF, 0xE0, 0, 0])
const png = Buffer.from([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A])
const gif = Buffer.from([0x47, 0x49, 0x46, 0x38, 0x39, 0x61])
const webp = Buffer.from([0x52, 0x49, 0x46, 0x46, 0, 0, 0, 0, 0x57, 0x45, 0x42, 0x50])
const junk = Buffer.from([0x00, 0x01, 0x02, 0x03])
assert.equal(sniffMime(jpeg), 'image/jpeg')
assert.equal(sniffMime(png), 'image/png')
assert.equal(sniffMime(gif), 'image/gif')
assert.equal(sniffMime(webp), 'image/webp')
assert.equal(sniffMime(junk), 'application/octet-stream')
assert.equal(sniffMime(Buffer.alloc(0)), 'application/octet-stream')
})
test('isSafeCid rejects path traversal and oversized/empty cids', () => {
assert.ok(isSafeCid('bafkreiabcdef123'))
assert.ok(!isSafeCid('../../../etc/passwd'))
assert.ok(!isSafeCid('a/b'))
assert.ok(!isSafeCid(''))
assert.ok(!isSafeCid(null))
assert.ok(!isSafeCid(undefined))
assert.ok(!isSafeCid('x'.repeat(129)))
})