|
1 | | -import { toast } from 'svelte-sonner'; |
| 1 | +import { HashBuffer } from '$lib/utils/crypto'; |
| 2 | + |
| 3 | +export const FirmwareChannels = ['stable', 'beta', 'develop'] as const; |
| 4 | +export type FirmwareChannel = (typeof FirmwareChannels)[number]; |
| 5 | + |
| 6 | +const BASE_URL = 'https://firmware.openshock.org'; |
| 7 | + |
| 8 | +const versionUrl = (channel: string) => `${BASE_URL}/version-${channel}.txt`; |
| 9 | +const boardsListUrl = (version: string) => `${BASE_URL}/${version}/boards.txt`; |
| 10 | +const boardFileUrl = (version: string, board: string, fileName: string) => |
| 11 | + `${BASE_URL}/${version}/${board}/${fileName}`; |
2 | 12 |
|
3 | 13 | async function DownloadText(url: string) { |
4 | | - try { |
5 | | - const response = await fetch(url); |
6 | | - if (!response.ok) return null; |
7 | | - const text = await response.text(); |
8 | | - return text.trim(); |
9 | | - } catch (e) { |
10 | | - console.error(e); |
11 | | - toast.error(`Failed to fetch ${url}`); |
12 | | - return null; |
13 | | - } |
| 14 | + const response = await fetch(url); |
| 15 | + if (!response.ok) |
| 16 | + throw new Error(`Failed to fetch ${url}: ${response.status} ${response.statusText}`); |
| 17 | + const text = await response.text(); |
| 18 | + return text.trim(); |
14 | 19 | } |
15 | 20 | async function DownloadLines(url: string) { |
16 | 21 | const text = await DownloadText(url); |
17 | | - if (!text) return null; |
18 | | - |
19 | 22 | return text.split('\n').map((x) => x.trim()); |
20 | 23 | } |
21 | | -async function DownloadBinary(url: string, onProgress: (progress: number) => void) { |
| 24 | +async function DownloadBinary(url: string) { |
22 | 25 | const response = await fetch(url); |
23 | | - if (!response.ok) return null; |
24 | | - |
25 | | - const contentLength = parseInt(response.headers.get('content-length')?.trim() ?? '0'); |
26 | | - const reader = response.body?.getReader(); |
27 | | - if (!reader) return null; |
28 | | - |
29 | | - console.log(`Downloading ${url} (${contentLength} bytes)`); |
30 | | - |
31 | | - let receivedLength = 0; |
32 | | - const chunks: Uint8Array[] = []; |
33 | | - for (;;) { |
34 | | - const { done, value } = await reader.read(); |
35 | | - if (done) break; |
36 | | - if (!value) continue; |
37 | | - chunks.push(value); |
38 | | - if (contentLength > 0) { |
39 | | - receivedLength += value.length; |
40 | | - onProgress(receivedLength / contentLength); |
41 | | - } |
42 | | - } |
43 | | - |
44 | | - const blob = new Blob(chunks); |
45 | | - |
46 | | - return await blob.arrayBuffer(); |
| 26 | + if (!response.ok) |
| 27 | + throw new Error(`Failed to fetch ${url}: ${response.status} ${response.statusText}`); |
| 28 | + return await response.bytes(); |
47 | 29 | } |
48 | 30 |
|
49 | | -export const FirmwareChannels = ['stable', 'beta', 'develop'] as const; |
50 | | -export type FirmwareChannel = (typeof FirmwareChannels)[number]; |
51 | | - |
52 | | -export async function FetchChannelVersion(channel: FirmwareChannel) { |
53 | | - return (await DownloadText(`https://firmware.openshock.org/version-${channel}.txt`))?.trim(); |
| 31 | +export function FetchChannelVersion(channel: FirmwareChannel) { |
| 32 | + return DownloadText(versionUrl(channel)); |
54 | 33 | } |
55 | 34 |
|
56 | 35 | export function FetchVersionBoards(version: string) { |
57 | | - return DownloadLines(`https://firmware.openshock.org/${version}/boards.txt`); |
| 36 | + return DownloadLines(boardsListUrl(version)); |
| 37 | +} |
| 38 | + |
| 39 | +export function DownloadBoardBinary(version: string, board: string, filename: string) { |
| 40 | + return DownloadBinary(boardFileUrl(version, board, filename)); |
58 | 41 | } |
59 | 42 |
|
60 | | -export function DownloadFirmwareBinary( |
| 43 | +export async function GetBoardBinaryHashes( |
61 | 44 | version: string, |
62 | 45 | board: string, |
63 | | - onProgress: (percent: number) => void |
| 46 | + hashType: 'md5' | 'sha256' = 'sha256' |
64 | 47 | ) { |
65 | | - return DownloadBinary( |
66 | | - `https://firmware.openshock.org/${version}/${board}/firmware.bin`, |
67 | | - onProgress |
68 | | - ); |
| 48 | + const lines = await DownloadLines(boardFileUrl(version, board, `hashes.${hashType}.txt`)); |
| 49 | + |
| 50 | + let hashLength: number; |
| 51 | + switch (hashType) { |
| 52 | + case 'md5': |
| 53 | + hashLength = 32; |
| 54 | + break; |
| 55 | + case 'sha256': |
| 56 | + hashLength = 64; |
| 57 | + break; |
| 58 | + default: |
| 59 | + throw new Error(`Unsupported hash type: ${hashType}`); |
| 60 | + } |
| 61 | + |
| 62 | + const hashes: Record<string, string> = {}; |
| 63 | + for (const line of lines) { |
| 64 | + const parts = line.split(' '); |
| 65 | + if (parts.length < 2) throw new Error(`Invalid hash line: ${line}`); |
| 66 | + const hash = parts[0].trim(); |
| 67 | + if (hash.length !== hashLength) throw new Error(`Invalid hash length in line: ${line}`); |
| 68 | + if (!/^[a-f0-9]+$/i.test(hash)) throw new Error(`Invalid hash format in line: ${line}`); |
| 69 | + |
| 70 | + let filename = parts.slice(1).join(' ').trim(); // Join the rest in case filename has spaces |
| 71 | + if (!filename) throw new Error(`Invalid filename in line: ${line}`); |
| 72 | + |
| 73 | + if (filename.startsWith('./')) { |
| 74 | + // Remove leading './' if present |
| 75 | + filename = filename.slice(2); |
| 76 | + } |
| 77 | + |
| 78 | + hashes[filename] = hash; |
| 79 | + } |
| 80 | + |
| 81 | + return hashes; |
69 | 82 | } |
| 83 | +export async function GetBoardBinaryHash( |
| 84 | + version: string, |
| 85 | + board: string, |
| 86 | + filename: string, |
| 87 | + hashType: 'md5' | 'sha256' |
| 88 | +) { |
| 89 | + if (filename.startsWith('./')) { |
| 90 | + filename = filename.slice(2); // Remove leading './' if present |
| 91 | + } |
70 | 92 |
|
71 | | -export async function GetFirmwareBinaryHash(version: string, board: string) { |
72 | | - const lines = await DownloadLines( |
73 | | - `https://firmware.openshock.org/${version}/${board}/hashes.md5.txt` |
74 | | - ); |
75 | | - if (!lines) return null; |
| 93 | + const hashes = await GetBoardBinaryHashes(version, board, hashType); |
| 94 | + if (filename in hashes) { |
| 95 | + return hashes[filename]; |
| 96 | + } |
76 | 97 |
|
77 | | - const hashLine = lines.find((x) => x.endsWith('firmware.bin')); |
78 | | - if (!hashLine) return null; |
| 98 | + return null; |
| 99 | +} |
79 | 100 |
|
80 | | - const hash = hashLine.split(' ')[0].trim(); |
| 101 | +export async function DownloadAndVerifyBoardBinary( |
| 102 | + version: string, |
| 103 | + board: string, |
| 104 | + filename: string |
| 105 | +) { |
| 106 | + // Download the binary and its hash in parallel |
| 107 | + const [binary, hash] = await Promise.all([ |
| 108 | + DownloadBinary(boardFileUrl(version, board, filename)), |
| 109 | + GetBoardBinaryHash(version, board, filename, 'sha256'), |
| 110 | + ]); |
| 111 | + |
| 112 | + if (!hash) { |
| 113 | + throw new Error(`No hash found for ${filename} in board ${board} version ${version}`); |
| 114 | + } |
81 | 115 |
|
82 | | - // Validate hash length |
83 | | - if (hash.length != 32) return null; |
| 116 | + // Calculate the hash of the downloaded binary |
| 117 | + const calculatedHash = await HashBuffer(binary, 'SHA-256'); |
| 118 | + if (calculatedHash !== hash) { |
| 119 | + throw new Error( |
| 120 | + `Hash mismatch for ${filename} in board ${board} version ${version}: expected ${hash}, got ${calculatedHash}` |
| 121 | + ); |
| 122 | + } |
84 | 123 |
|
85 | | - return hash; |
| 124 | + return binary; |
86 | 125 | } |
0 commit comments