← Public packages
@noah/mega-radio
MEGA Radio (the WAKE album) for members of the MEGA.dev Discord: sign in with Kody, verify with Discord, listen with repeat.
Files
/**
* MEGA Radio tracks and covers live in this package's own storage (SQLite), not in the published tree:
* Kody's publish checks measure every file as UTF-8 text, so an MP3 over about 5.5 MiB cannot be
* published. Each file is stored as base64 chunks of AUDIO_CHUNK_BYTES raw bytes and served back byte for
* byte (with Range support) at /files/radio/NN.(mp3|png) (key `radio/NN.(mp3|png)`), only to verified
* MEGA.dev Discord members (the gate is in app.ts). scripts/upload-radio.ts fills it through the
* ./audio-store export.
* Runtime-free: it takes the SQL runner as an argument.
*/
export const AUDIO_CHUNK_BYTES = 512 * 1024
/** runs one SQL statement with positional bindings and returns its rows */
export type Sql = (query: string, bindings?: unknown[]) => Promise<Record<string, unknown>[]>
type Meta = { code: string; bytes: number; chunk_bytes: number; chunks: number; sha256: string; stored: number }
const KEYS: Record<string, string[]> = {
begin: ['action', 'code', 'bytes', 'sha256'],
put: ['action', 'code', 'index', 'data'],
status: ['action', 'code'],
verify: ['action', 'code'],
remove: ['action', 'code'],
store: ['action', 'code', 'sha256', 'data'],
list: ['action', 'prefix'],
}
const FILE_KEY = /^radio\/\d{2}\.(mp3|png)$/
const text = (body: string, status: number) => new Response(body, { status, headers: { 'content-type': 'text/plain; charset=utf-8' } })
/**
* Decode base64 text to bytes.
*
* @param data - base64
* @returns the decoded bytes
*/
function fromBase64(data: string): Uint8Array {
const binary = atob(data)
const bytes = new Uint8Array(binary.length)
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i)
return bytes
}
/**
* Hash bytes with SHA-256.
*
* @param bytes - raw bytes
* @returns the lower-case hex digest
*/
async function sha256Hex(bytes: Uint8Array): Promise<string> {
return Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256', bytes as unknown as ArrayBuffer)), (b) => b.toString(16).padStart(2, '0')).join('')
}
/**
* Normalize and validate a stored file's key.
*
* @param code - `radio/NN.(mp3|png)`
* @returns the lower-case key
*/
function fileKey(code: unknown): string {
const key = typeof code === 'string' ? code.toLowerCase() : ''
if (!FILE_KEY.test(key)) throw new Error('code must look like radio/01.mp3 or radio/01.png')
return key
}
/**
* Parse a single-range `Range` header against a known size.
*
* @param header - the request's Range header, if any
* @param size - total size in bytes
* @returns the inclusive range, null for the whole file, or 'invalid' when it cannot be satisfied
*/
export function parseRange(header: string | null, size: number): { start: number; end: number } | null | 'invalid' {
const m = /^bytes=(\d*)-(\d*)$/.exec(header ?? '')
if (!m || (!m[1] && !m[2])) return null
const start = m[1] ? Number(m[1]) : Math.max(0, size - Number(m[2]))
const end = m[1] && m[2] ? Math.min(Number(m[2]), size - 1) : size - 1
return start > end || start >= size ? 'invalid' : { start, end }
}
/**
* Build the audio store on top of a SQL runner.
*
* @param sql - runs one statement against the package's storage
* @returns `manage` (the upload API) and `serve` (the streaming handler)
*/
export function createAudioStore(sql: Sql) {
let ready: Promise<unknown> | null = null
const ensureSchema = () =>
(ready ??= (async () => {
await sql('CREATE TABLE IF NOT EXISTS audio_meta (code TEXT PRIMARY KEY, bytes INTEGER NOT NULL, chunk_bytes INTEGER NOT NULL, chunks INTEGER NOT NULL, sha256 TEXT NOT NULL)')
await sql('CREATE TABLE IF NOT EXISTS audio_chunk (code TEXT NOT NULL, idx INTEGER NOT NULL, data TEXT NOT NULL, PRIMARY KEY (code, idx))')
})().catch((error) => {
ready = null
throw error
}))
/**
* Load a stored file's metadata and how many chunks are stored.
*
* @param code - file key, lower case
* @returns the metadata, or null when nothing was uploaded
*/
async function loadMeta(code: string): Promise<Meta | null> {
await ensureSchema()
const [meta] = await sql('SELECT code, bytes, chunk_bytes, chunks, sha256 FROM audio_meta WHERE code = ?', [code])
if (!meta) return null
const [count] = await sql('SELECT COUNT(*) AS n FROM audio_chunk WHERE code = ?', [code])
return {
code: String(meta.code),
bytes: Number(meta.bytes),
chunk_bytes: Number(meta.chunk_bytes),
chunks: Number(meta.chunks),
sha256: String(meta.sha256),
stored: Number(count?.n ?? 0),
}
}
/**
* Read one stored chunk.
*
* @param code - file key, lower case
* @param index - zero-based chunk index
* @returns the chunk's bytes
*/
async function chunk(code: string, index: number): Promise<Uint8Array> {
const [row] = await sql('SELECT data FROM audio_chunk WHERE code = ? AND idx = ?', [code, index])
if (!row) throw new Error(`chunk ${index} of ${code} is missing`)
return fromBase64(String(row.data))
}
/**
* Manage the stored audio (used by scripts/upload-radio.ts).
*
* @param params - `{ action: 'begin', code, bytes, sha256 }` records a file's size and hash (keeping chunks
* already stored for the same file); `{ action: 'put', code, index, data }` stores one base64 chunk;
* `{ action: 'status', code }` lists missing chunks; `{ action: 'verify', code }` re-hashes the stored bytes;
* `{ action: 'remove', code }` deletes them; `{ action: 'store', code, sha256, data }` stores a whole file of
* at most one chunk in one call (checking its hash); `{ action: 'list', prefix }` lists stored files by key prefix
* @returns a small JSON summary, never the file itself
*/
async function manage(params: Record<string, unknown> = {}) {
const action = String(params.action ?? '')
const allowed = KEYS[action]
if (!allowed) throw new Error(`Unknown action "${action}". Use one of: ${Object.keys(KEYS).join(', ')}`)
const extra = Object.keys(params).filter((k) => !allowed.includes(k))
if (extra.length) throw new Error(`Unknown key(s) for ${action}: ${extra.join(', ')}`)
await ensureSchema()
if (action === 'list') {
const prefix = String(params.prefix ?? '').toLowerCase()
const rows = await sql('SELECT m.code AS code, m.bytes AS bytes, m.chunks AS chunks, m.sha256 AS sha256, (SELECT COUNT(*) FROM audio_chunk c WHERE c.code = m.code) AS stored FROM audio_meta m WHERE substr(m.code, 1, ?) = ? ORDER BY m.code', [prefix.length, prefix])
return { files: rows.map((r) => ({ code: String(r.code), bytes: Number(r.bytes), sha256: String(r.sha256), complete: Number(r.stored) === Number(r.chunks) })) }
}
const code = fileKey(params.code)
if (action === 'store') {
const data = String(params.data ?? '')
const bytes = fromBase64(data)
if (bytes.length === 0 || bytes.length > AUDIO_CHUNK_BYTES) throw new Error(`store takes 1-${AUDIO_CHUNK_BYTES} bytes; use begin and put for larger files`)
const digest = await sha256Hex(bytes)
if (digest !== params.sha256) throw new Error(`sha256 mismatch: the data hashes to ${digest}`)
await sql('DELETE FROM audio_chunk WHERE code = ?', [code])
await sql('INSERT OR REPLACE INTO audio_meta (code, bytes, chunk_bytes, chunks, sha256) VALUES (?, ?, ?, 1, ?)', [code, bytes.length, AUDIO_CHUNK_BYTES, digest])
await sql('INSERT INTO audio_chunk (code, idx, data) VALUES (?, 0, ?)', [code, data])
return { code, bytes: bytes.length, sha256: digest }
}
if (action === 'begin') {
const bytes = Number(params.bytes)
const sha256 = String(params.sha256 ?? '')
if (!Number.isInteger(bytes) || bytes <= 0) throw new Error('bytes must be a positive integer')
if (!/^[0-9a-f]{64}$/.test(sha256)) throw new Error('sha256 must be 64 lower-case hex characters')
const chunks = Math.ceil(bytes / AUDIO_CHUNK_BYTES)
const existing = await loadMeta(code)
if (existing && existing.sha256 === sha256 && existing.bytes === bytes && existing.chunk_bytes === AUDIO_CHUNK_BYTES) return { code, chunks, kept: existing.stored }
await sql('DELETE FROM audio_chunk WHERE code = ?', [code])
await sql('INSERT OR REPLACE INTO audio_meta (code, bytes, chunk_bytes, chunks, sha256) VALUES (?, ?, ?, ?, ?)', [code, bytes, AUDIO_CHUNK_BYTES, chunks, sha256])
return { code, chunks, kept: 0 }
}
const meta = await loadMeta(code)
if (!meta) {
if (action === 'remove') return { code, removed: false }
throw new Error(`No audio started for ${code}; call begin first`)
}
if (action === 'put') {
const index = Number(params.index)
if (!Number.isInteger(index) || index < 0 || index >= meta.chunks) throw new Error(`index must be 0-${meta.chunks - 1}`)
const data = String(params.data ?? '')
const size = fromBase64(data).length
const expected = Math.min(meta.chunk_bytes, meta.bytes - index * meta.chunk_bytes)
if (size !== expected) throw new Error(`chunk ${index} is ${size} bytes, expected ${expected}`)
await sql('INSERT OR REPLACE INTO audio_chunk (code, idx, data) VALUES (?, ?, ?)', [code, index, data])
return { code, index, size }
}
if (action === 'status') {
const have = new Set((await sql('SELECT idx FROM audio_chunk WHERE code = ?', [code])).map((r) => Number(r.idx)))
const missing = Array.from({ length: meta.chunks }, (_, i) => i).filter((i) => !have.has(i))
return { code, bytes: meta.bytes, chunks: meta.chunks, stored: have.size, missing, sha256: meta.sha256 }
}
if (action === 'verify') {
if (meta.stored !== meta.chunks) return { code, ok: false, reason: `${meta.stored} of ${meta.chunks} chunks stored` }
const all = new Uint8Array(meta.bytes)
for (let i = 0; i < meta.chunks; i++) all.set(await chunk(code, i), i * meta.chunk_bytes)
const digest = await sha256Hex(all)
return { code, ok: digest === meta.sha256, bytes: meta.bytes, sha256: digest }
}
await sql('DELETE FROM audio_chunk WHERE code = ?', [code])
await sql('DELETE FROM audio_meta WHERE code = ?', [code])
return { code, removed: true }
}
/**
* Stream a stored file, honoring Range requests so players can seek.
*
* @param request - the incoming request (GET or HEAD)
* @param code - the file key, any case
* @param fileName - download name used when `?download=1` is set
* @param contentType - the file's media type
* @returns the file response, 404 when not uploaded, or 503 while an upload is incomplete
*/
async function serve(request: Request, code: string, fileName: string, contentType = 'audio/mpeg'): Promise<Response> {
if (request.method !== 'GET' && request.method !== 'HEAD') return new Response('Method not allowed', { status: 405, headers: { allow: 'GET, HEAD' } })
const meta = await loadMeta(code.toLowerCase())
if (!meta) return text('This file is not stored yet.', 404)
if (meta.stored !== meta.chunks) return text(`Upload incomplete (${meta.stored} of ${meta.chunks} chunks).`, 503)
const etag = `"${meta.sha256}"`
const headers: Record<string, string> = { 'content-type': contentType, 'accept-ranges': 'bytes', etag, 'cache-control': 'private, no-store' }
if (new URL(request.url).searchParams.get('download')) headers['content-disposition'] = `attachment; filename="${fileName}"`
if (request.headers.get('if-none-match') === etag) return new Response(null, { status: 304, headers })
const range = parseRange(request.headers.get('range'), meta.bytes)
if (range === 'invalid') return new Response(null, { status: 416, headers: { 'content-range': `bytes */${meta.bytes}` } })
const { start, end } = range ?? { start: 0, end: meta.bytes - 1 }
headers['content-length'] = String(end - start + 1)
if (range) headers['content-range'] = `bytes ${start}-${end}/${meta.bytes}`
const status = range ? 206 : 200
if (request.method === 'HEAD') return new Response(null, { status, headers })
let next = Math.floor(start / meta.chunk_bytes)
const last = Math.floor(end / meta.chunk_bytes)
const body = new ReadableStream<Uint8Array>({
async pull(controller) {
if (next > last) return controller.close()
const bytes = await chunk(meta.code, next)
const offset = next * meta.chunk_bytes
controller.enqueue(bytes.subarray(Math.max(0, start - offset), Math.min(bytes.length, end - offset + 1)))
next++
},
})
return new Response(body, { status, headers })
}
return { manage, serve }
}
/**
* Encode bytes as base64.
*
* @param bytes - raw bytes
* @returns base64 text
*/
function toBase64(bytes: Uint8Array): string {
let binary = ''
for (let i = 0; i < bytes.length; i += 0x8000) binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000))
return btoa(binary)
}
/**
* Upload a file into the store chunk by chunk, skipping chunks already stored, then verify it.
*
* @param code - file key
* @param mp3 - the whole file
* @param sha256 - its hex digest
* @param call - sends one `manage` request (directly, or through the Kody CLI)
* @param log - progress output
* @returns the verify result
*/
export async function uploadAudio(code: string, mp3: Uint8Array, sha256: string, call: (params: Record<string, unknown>) => Promise<any>, log: (line: string) => void = () => {}) {
const begun = await call({ action: 'begin', code, bytes: mp3.length, sha256 })
const status = await call({ action: 'status', code })
log(`${code}: ${begun.chunks} chunk(s), ${status.stored} already stored, ${status.missing.length} to send`)
for (const index of status.missing as number[]) {
await call({ action: 'put', code, index, data: toBase64(mp3.subarray(index * AUDIO_CHUNK_BYTES, (index + 1) * AUDIO_CHUNK_BYTES)) })
log(`${code}: chunk ${index + 1}/${begun.chunks}`)
}
return call({ action: 'verify', code })
}
const FILE_TYPES: Record<string, string> = { png: 'image/png', mp3: 'audio/mpeg' }
/**
* Match a radio track or cover URL path (`/files/radio/NN.(mp3|png)`).
*
* @param pathname - the request path inside the app
* @returns the storage key, track number, media type and download name, or null for any other path
*/
export function fileRoute(pathname: string): { key: string; n: number; type: string; name: string } | null {
const m = /^\/files\/(radio\/(\d{2})\.(mp3|png))$/i.exec(pathname)
if (!m) return null
const key = m[1].toLowerCase()
return { key, n: Number(m[2]), type: FILE_TYPES[m[3].toLowerCase()], name: key.replace('/', '-') }
}