diff --git a/.vitepress/theme/components/NokiaFirmware.vue b/.vitepress/theme/components/NokiaFirmware.vue new file mode 100644 index 00000000..02736c2a --- /dev/null +++ b/.vitepress/theme/components/NokiaFirmware.vue @@ -0,0 +1,468 @@ + + + + + diff --git a/.vitepress/theme/index.ts b/.vitepress/theme/index.ts index 88d7b39b..d8914a3b 100644 --- a/.vitepress/theme/index.ts +++ b/.vitepress/theme/index.ts @@ -9,6 +9,7 @@ import HisensePloam from './components/HisensePloam.vue' import ImageFigure from './components/ImageFigure.vue' import LantiqEeprom from './components/LantiqEeprom.vue' import Mermaid from './components/Mermaid.vue' +import NokiaFirmware from './components/NokiaFirmware.vue' import NokiaSerial from './components/NokiaSerial.vue' import OmciVlanParser from './components/OmciVlanParser.vue' import RootLantiq from './components/RootLantiq.vue' @@ -28,6 +29,7 @@ export default { app.component('ImageFigure', ImageFigure) app.component('LantiqEeprom', LantiqEeprom) app.component('Mermaid', Mermaid) + app.component('NokiaFirmware', NokiaFirmware) app.component('NokiaSerial', NokiaSerial) app.component('OmciVlanParser', OmciVlanParser) app.component('RootLantiq', RootLantiq) diff --git a/.vitepress/theme/lib/nokiaConsole.js b/.vitepress/theme/lib/nokiaConsole.js new file mode 100644 index 00000000..2dd6301c --- /dev/null +++ b/.vitepress/theme/lib/nokiaConsole.js @@ -0,0 +1,256 @@ +// Shared verified FALCON console transport for Nokia UART tools. +const PROMPT = /(?:^|\n)[ \t]*FALCON[ \t]*=>[ \t]*$/; +const ROM = /(?:^|\n)[ \t]*ROM:/; +const STARTUP = /(?:^|\n)[ \t]*(?:U-Boot\b|Chip:|Bootmode:|Reset cause:|CPU Clock:|Press SPACE|Hit any key|Autoboot)/; +const STARTUP_EVENTS = /(?:^|\n)[ \t]*(?:ROM:[ \t]*V|U-Boot\b|Chip:|Bootmode:|Reset cause:|CPU Clock:|Press SPACE|Hit any key|Autoboot)/g; +const LINUX = /(?:^|\n)[ \t]*(?:Starting kernel|Linux version |BusyBox |[^\n]*[Ll]ogin:[ \t]*$|root@[^\n]*[#$][ \t]*$)/m; +const RECOVERABLE = new Set(['BreakError', 'FramingError', 'ParityError']); +const MAX_OUTPUT = 256 * 1024; + +function failure(code, message) { + return Object.assign(new Error(message), { name: 'NokiaSerialError', code }); +} + +function cancelled() { + return new DOMException('The Nokia UART procedure was cancelled.', 'AbortError'); +} + +function checkAbort(signal) { + if (signal?.aborted) throw cancelled(); +} + +// A timed-out read remains owned by the session until it is consumed or closed. +// This avoids concurrent readers and losing bytes between polling intervals. +async function bounded(promise, ms, signal, error) { + if (signal?.aborted) { + // The caller may already have started an I/O request when abort fires. + // Observe a late rejection even though this operation cannot continue. + Promise.resolve(promise).catch(() => {}); + throw cancelled(); + } + let timer; + let abort; + const interrupted = new Promise((_, reject) => { + if (ms !== undefined) timer = setTimeout(() => reject(error), Math.max(0, ms)); + abort = () => reject(cancelled()); + signal?.addEventListener('abort', abort, { once: true }); + }); + try { + return await Promise.race([promise, interrupted]); + } finally { + clearTimeout(timer); + signal?.removeEventListener('abort', abort); + } +} + +function normalize(text) { + return text.replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, '').replace(/\r\n?/g, '\n'); +} + +function checkConsole(text, command = false, versionReply = false) { + if (/bad\s+crc[^\n]*using\s+default\s+environment/i.test(text)) { + throw failure('BAD_ENVIRONMENT', 'U-Boot reported an invalid saved environment and is using defaults. Review or restore the environment before configuring or flashing the module.'); + } + if (/ROM:\s*Boot\?|Boot\?\s*\(0-9A-F/i.test(text)) { + throw failure('BOOTROM_MENU', 'The module is at the BootROM recovery menu, not the FALCON U-Boot console. Use the documented Nokia recovery procedure.'); + } + if (LINUX.test(text)) { + throw failure('LINUX_CONSOLE', 'The module has booted into Linux. Use SSH to enable UART, or power-cycle the module and retry to stop U-Boot.'); + } + // `version` legitimately prints the U-Boot banner. Permit only that line + // for that exact command; ROM/Chip/Bootmode/etc. still signal a restart. + const startupText = versionReply ? text.replace(/^U-Boot[^\n]*(?:\n|$)/gm, '') : text; + if (command && (ROM.test(text) || STARTUP.test(startupText))) { + throw failure('DISCONNECTED', 'The module restarted during the command. No further commands will be sent.'); + } +} + +class NokiaConsole { + constructor(port, { signal, baudRate, startupTimeoutMs, commandTimeoutMs, ioTimeoutMs }) { + Object.assign(this, { port, signal, baudRate, startupTimeoutMs, commandTimeoutMs, ioTimeoutMs }); + this.buffer = ''; + this.decoder = new TextDecoder(); + this.encoder = new TextEncoder(); + this.verified = false; + this.readErrors = 0; + this.bytes = new Uint8Array(); + this.byteOffset = 0; + } + + async open() { + checkAbort(this.signal); + this.opening = this.port.open({ baudRate: this.baudRate, dataBits: 8, stopBits: 1, parity: 'none', flowControl: 'none' }); + await bounded(this.opening, this.ioTimeoutMs, this.signal, failure('TIMEOUT', 'Opening the serial port timed out.')); + this.opened = true; + this.reader = this.port.readable?.getReader(); + this.writer = this.port.writable?.getWriter(); + if (!this.reader || !this.writer) throw failure('DISCONNECTED', 'The serial port has no readable/writable connection.'); + } + + async write(text, deadline) { + return this.writeBytes(this.encoder.encode(text), deadline); + } + + async writeBytes(bytes, deadline, signal = this.signal) { + checkAbort(signal); + if (!this.writer) throw failure('DISCONNECTED', 'The serial connection is closed.'); + const remaining = Math.min(this.ioTimeoutMs, deadline - Date.now()); + if (remaining <= 0) throw failure('TIMEOUT', 'The serial operation timed out.'); + try { + await bounded(this.writer.write(bytes), remaining, signal, + failure('TIMEOUT', 'Writing to the serial port timed out.')); + } catch (error) { + if (error.name === 'AbortError' || error.code) throw error; + throw failure('DISCONNECTED', `Could not write to the serial port: ${error.message}`); + } + } + + async readRaw(deadline, pollMs = Infinity, recover = false) { + checkAbort(this.signal); + if (this.byteOffset < this.bytes.length) { + const bytes = this.bytes.subarray(this.byteOffset); + this.bytes = new Uint8Array(); + this.byteOffset = 0; + return bytes; + } + if (!this.pendingRead) this.pendingRead = this.reader.read(); + let result; + try { + result = await bounded(this.pendingRead, Math.min(pollMs, deadline - Date.now()), this.signal, + failure('POLL', 'Waiting for serial data.')); + } catch (error) { + if (error.code === 'POLL') return null; + this.pendingRead = undefined; + // Web Serial replaces its readable stream after these nonfatal + // errors (FTDI adapters can report BREAK during module insertion). + if (recover && RECOVERABLE.has(error.name) && ++this.readErrors <= 5) { + this.reader.releaseLock(); + this.reader = this.port.readable?.getReader(); + this.decoder = new TextDecoder(); + if (this.reader) return new Uint8Array(); + } + if (error.name === 'AbortError') throw error; + throw failure('DISCONNECTED', `Serial reading failed (${error.name}): ${error.message}. Check the adapter, wiring and 115200 8-N-1 settings.`); + } + this.pendingRead = undefined; + if (result.done) throw failure('DISCONNECTED', 'The serial connection closed before the procedure completed.'); + return result.value; + } + + async read(deadline, pollMs = Infinity) { + const bytes = await this.readRaw(deadline, pollMs, true); + if (bytes === null) return false; + this.buffer += this.decoder.decode(bytes, { stream: true }); + if (this.buffer.length > MAX_OUTPUT) throw failure('TIMEOUT', 'Too much serial output was received without a FALCON prompt.'); + return true; + } + + // YMODEM consumes individual bytes, preserving coalesced ACK/C/prompt data. + // Stream/framing errors during binary transfer are fatal; only the text + // console may recover its readable stream after an FTDI BREAK. + async readByte(deadline, signal = this.signal) { + checkAbort(signal); + while (this.byteOffset >= this.bytes.length) { + if (Date.now() >= deadline) throw failure('TIMEOUT', 'Waiting for serial data timed out.'); + const bytes = await this.readRaw(deadline); + this.bytes = bytes ?? new Uint8Array(); + this.byteOffset = 0; + checkAbort(signal); + } + return this.bytes[this.byteOffset++]; + } + + async acquire() { + this.verified = false; + const deadline = Date.now() + this.startupTimeoutMs; + await this.write('\r', deadline); // Also elicit a prompt from an idle U-Boot. + let lastEvent = -1; + let interruptUntil = 0; + let nextInterrupt = 0; + while (Date.now() < deadline) { + checkAbort(this.signal); + const text = normalize(this.buffer); + checkConsole(text); + if (PROMPT.test(text)) { + this.buffer = ''; + const bytes = crypto.getRandomValues(new Uint8Array(12)); + const nonce = '__NOKIA_UART_' + Array.from(bytes, b => b.toString(16).padStart(2, '0')).join('') + '__'; + const response = await this.exchange(`echo ${nonce}`, Math.min(deadline, Date.now() + this.commandTimeoutMs)); + if (!normalize(response).split('\n').some(line => line.trim() === nonce)) { + throw failure('UNVERIFIED', 'The FALCON prompt did not return the console verification response. No settings were changed.'); + } + this.verified = true; + return; + } + const events = Array.from(text.matchAll(STARTUP_EVENTS)); + const latest = events.at(-1)?.index ?? -1; + if (latest > lastEvent) { + lastEvent = latest; + interruptUntil = Math.min(deadline, Date.now() + 5000); + nextInterrupt = Date.now(); + } + if (Date.now() < interruptUntil && Date.now() >= nextInterrupt) { + await this.write('\x03', deadline); + nextInterrupt = Date.now() + 50; + } + await this.read(deadline, Date.now() < interruptUntil ? Math.max(1, nextInterrupt - Date.now()) : Infinity); + } + const text = normalize(this.buffer); + if (ROM.test(text) && !STARTUP.test(text)) { + throw failure('ROM_ONLY', 'Only BootROM output was received; an interactive U-Boot prompt was not obtained. The UART console may be disabled by asc0=3. Enable it through SSH or the supported web interface, or use the documented Nokia recovery procedure if network access is unavailable. No settings were changed.'); + } + throw failure('TIMEOUT', 'Timed out waiting for a verified FALCON prompt. Check the Nokia pinout and power-cycle the module after starting this procedure. No settings were changed.'); + } + + async exchange(command, deadline) { + await this.write(command + '\r', deadline); + return this.waitPrompt(deadline, command.split(' ')[0]); + } + + async waitPrompt(deadline, operation = 'transfer') { + while (Date.now() < deadline) { + await this.read(deadline); + const text = normalize(this.buffer); + checkConsole(text, true, operation === 'version'); + const prompt = PROMPT.exec(text); + if (prompt) { + this.buffer = ''; + return text.slice(0, prompt.index); + } + } + throw failure('TIMEOUT', `U-Boot did not finish the ${operation} command in time. No further commands will be sent.`); + } + + async command(command, timeoutMs = this.commandTimeoutMs) { + if (!this.verified) throw failure('UNVERIFIED', 'A verified FALCON console is required before sending commands.'); + try { + return await this.exchange(command, Date.now() + timeoutMs); + } catch (error) { + this.verified = false; + throw error; + } + } + + async close() { + this.verified = false; + if (!this.opened) { + // An open request may finish after its timeout or user cancellation. + this.opening?.then(() => this.port.close()).catch(() => {}); + return; + } + const limit = Math.min(1000, this.ioTimeoutMs); + const cleanup = promise => bounded(Promise.resolve(promise).catch(() => {}), limit, undefined, + failure('TIMEOUT', 'Serial cleanup timed out.')).catch(() => {}); + await Promise.all([cleanup(this.reader?.cancel()), cleanup(this.writer?.abort())]); + try { this.reader?.releaseLock(); } catch { /* A disconnected stream can already be released. */ } + try { this.writer?.releaseLock(); } catch { /* A disconnected stream can already be released. */ } + await cleanup(this.port.close()); + } +} + +function commandFailed(response) { + return /\b(?:error|failed|failure|bad crc|unknown command|timeout|timed out)\b|^\s*Usage:/im.test(response); +} + + +export { NokiaConsole, failure, cancelled, checkAbort, bounded, normalize, commandFailed }; diff --git a/.vitepress/theme/lib/nokiaFirmware.js b/.vitepress/theme/lib/nokiaFirmware.js new file mode 100644 index 00000000..26c75b9f --- /dev/null +++ b/.vitepress/theme/lib/nokiaFirmware.js @@ -0,0 +1,301 @@ +import { NokiaConsole, bounded, cancelled, checkAbort, normalize, commandFailed } from './nokiaConsole.js'; +import { inspectNokiaImage, crc32Hex, NOKIA_SLOT_SIZE } from './nokiaImage.js'; +import { sendYmodem } from './ymodem.js'; + +// Inspected G-010S-A legacy boot chain. Values are compared, never executed by +// this tool. Device identifiers, optical calibration and network settings are +// deliberately absent. Unknown boot scripts require another reviewed profile. +export const NOKIA_BOOT_PROFILE = Object.freeze({ + "bootcmd": "run flash_flash", + "flash_flash": "run select_image boot_image", + "boot_image": "run boot_image${c_img};", + "boot_image0": "run kernel0_from_sf flashargs addip addmtdparts0 addmisc && bootm ${ram_addr}", + "boot_image1": "run kernel1_from_sf flashargs addip addmtdparts1 addmisc && bootm ${ram_addr}", + "kernel0_from_sf": "sf probe 0;sf read ${ram_addr} ${kernel0_offs} ${max_kernel_size}", + "kernel1_from_sf": "sf probe 0;sf read ${ram_addr} ${kernel1_offs} ${max_kernel_size}", + "addmtdparts0": "setenv mtdparts mtdparts=sflash:256k(uboot)ro,512k(uboot_env),6144k(linux),6144k(image1),1024k(configfs),2112k(logfs),64k(ri),64k(sfp),64k(ribackup)", + "addmtdparts1": "setenv mtdparts mtdparts=sflash:256k(uboot)ro,512k(uboot_env),6144k(image0),6144k(linux),1024k(configfs),2112k(logfs),64k(ri),64k(sfp),64k(ribackup)", + "kernel0_offs": "0xC0000", + "kernel1_offs": "0x6C0000", + "ram_addr": "80F00000", + "max_kernel_size": "180000", + "select_image": "if test -n $commit ; then else setenv commit _err;saveenv;fi;if test -n $image0_is_valid ; then else setenv image0_is_valid 1;saveenv;fi;if test -n $image1_is_valid ; then else setenv image1_is_valid 0;saveenv;fi;if itest *${magic_addr} == ${magic_val} ; then if itest *${act_img_addr} == 0 ; then setenv next_active 0;fi;if itest *${act_img_addr} == 1 ; then setenv next_active 1;fi;mw ${magic_addr} 0x0;mw ${act_img_addr} 0x0;fi;if test $next_active = -1 ; then setenv c_img $commit;else setenv c_img $next_active;if test $next_active != $commit ;then if test $next_active = 0 ;then setenv next_active 1;setenv commit 1;else setenv next_active 0;setenv commit 0;fi;saveenv;fi;fi;exit 0", + "magic_addr": "0xBF200038", + "magic_val": "0xDEADBEEF", + "act_img_addr": "0xBF20003C", + "addip": "setenv bootargs ${bootargs} ip=${ipaddr}:${serverip}:${gatewayip}:${netmask}:${hostname}:${netdev}:off", + "update_system": "run update_image0 && setenv commit 0 && setenv image0_is_valid 1 && saveenv", + "flashargs": "setenv bootargs rootfstype=squashfs,jffs2", + "addmisc": "setenv bootargs ${bootargs} ethaddr=${ethaddr} machtype=${machtype} vpe1_load_addr=0x83f00000 vpe1_mem=1M mem=63M ${mtdparts} quiet" +}); + +// Exact boot migration used by the inspected Nokia image /lib/upgrade/common.sh. +// Applying it after readback avoids a second sysupgrade overwriting the old slot. +export const NOKIA_UPGRADE_SETTINGS = Object.freeze({ + "boot_fail": "0", + "boot_image": "run boot_image${c_img};", + "update_system": "run update_image0 && setenv committed_image 0 && setenv image0_is_valid 1 && saveenv", + "select_image": "if test -n $committed_image ; then else setenv committed_image 0;saveenv;fi;if test -n $image0_is_valid ; then else setenv image0_is_valid 1;saveenv;fi;if test -n $image1_is_valid ; then else setenv image1_is_valid 0;saveenv;fi;if itest *${magic_addr} == ${magic_val} ; then if itest *${act_img_addr} == 0 ; then setenv next_active 0;fi;if itest *${act_img_addr} == 1 ; then setenv next_active 1;fi;mw ${magic_addr} 0x0;mw ${act_img_addr} 0x0;fi;if test $next_active = -1 ; then setenv c_img $committed_image;else setenv c_img $next_active;if test $next_active != $committed_image ;then if test $next_active = 0 ;then setenv next_active 1;setenv committed_image 1;else setenv next_active 0;setenv committed_image 0;fi;saveenv;fi;fi;setenv boot_fail 0;exit 0" +}); + +const VERSION = 'U-Boot 2015.04-lantiq-gpon-1.3.6.1 (Feb 07 2018 - 17:12:06)'; +const RAM = 0x80800000; +const OFFSETS = [0x0c0000, 0x6c0000]; +const CONTROLS = ['commit', 'committed_image', 'next_active', 'c_img', 'image0_is_valid', 'image1_is_valid', + 'boot_fail', 'asc0', 'bootdelay', 'preboot']; +const KEYS = [...Object.keys(NOKIA_BOOT_PROFILE), ...CONTROLS]; +const hex = n => '0x' + n.toString(16); +const canonical = value => value?.trim().replace(/\s+/g, ' '); + +function problem(code, message) { + return Object.assign(new Error(message), { name: 'NokiaFirmwareError', code }); +} + +function nonce() { + return '__NOKIA_FLASH_' + Array.from(crypto.getRandomValues(new Uint8Array(12)), + n => n.toString(16).padStart(2, '0')).join('') + '__'; +} + +async function checked(serial, command, timeoutMs) { + const token = nonce(); + // The inspected bootloader's readline buffer is 1024 bytes. Keep the + // complete quoted assignment, success marker and CR within that bound. + if (command.length + token.length + 11 > 1022) throw problem('COMMAND_LENGTH', 'The bootloader command exceeds its inspected input limit.'); + const response = await serial.command(`${command} && echo ${token}`, timeoutMs); + if (commandFailed(response) || !normalize(response).split('\n').some(line => line.trim() === token)) { + throw problem('COMMAND_FAILED', `U-Boot did not confirm ${command.split(' ')[0]}. No further commands will be sent.`); + } + return response; +} + +async function readEnvironment(serial) { + const result = {}; + for (const key of KEYS) { + const command = `printenv ${key}`; + const response = await serial.command(command); + const lines = normalize(response).split('\n').map(s => s.trim()).filter(s => + s && s !== command && s !== `FALCON => ${command}`); + if (lines.length === 1 && lines[0] === `## Error: "${key}" not defined`) { + result[key] = null; + } else if (lines.length === 1 && lines[0].startsWith(key + '=')) { + result[key] = lines[0].slice(key.length + 1); + } else { + throw problem('ENVIRONMENT', `Could not reliably read ${key}. The firmware was not written.`); + } + } + return result; +} + +function sameEnvironment(a, b) { + return KEYS.every(key => a[key] === b[key]); +} + +/** Choose the slot opposite the persistent committed slot, never saved c_img. */ +export function planNokiaFlash(settings, image, bootMode = 'trial') { + if (!['stage', 'trial', 'commit'].includes(bootMode)) throw problem('BOOT_MODE', 'Choose staging, a trial boot or a new default image.'); + const upgraded = canonical(settings.select_image) === canonical(NOKIA_UPGRADE_SETTINGS.select_image); + for (const [key, expected] of Object.entries(NOKIA_BOOT_PROFILE)) { + const supported = upgraded && key in NOKIA_UPGRADE_SETTINGS ? NOKIA_UPGRADE_SETTINGS[key] : expected; + if (canonical(settings[key]) !== canonical(supported)) { + throw problem('UNSUPPORTED_LAYOUT', `The ${key} setting does not match the supported Nokia boot profile. This tool will not guess a flash layout or rewrite unknown boot scripts.`); + } + } + const committed = settings[upgraded ? 'committed_image' : 'commit']; + if (!/^[01]$/.test(committed ?? '') || + ![committed, '-1'].includes(settings.next_active)) { + throw problem('BOOT_STATE', 'The committed image is ambiguous or a trial boot is pending. Boot and confirm the working image before flashing.'); + } + const protectedSlot = Number(committed); + const targetSlot = 1 - protectedSlot; + if (settings[`image${protectedSlot}_is_valid`] !== '1' || + !/^[01]$/.test(settings[`image${targetSlot}_is_valid`] ?? '') || + !/^[0-7]$/.test(settings.boot_fail ?? '')) { + throw problem('BOOT_STATE', 'The image validity or boot-failure state is not supported. Review the bootloader before flashing.'); + } + const delay = Number(settings.bootdelay); + if (settings.asc0 !== '0' || !/^\d+$/.test(settings.bootdelay ?? '') || + !Number.isSafeInteger(delay) || delay < 1 || delay > 0x7fffffff || + ![null, ''].includes(settings.preboot)) { + throw problem('UART_SETTINGS', 'Enable UART with a positive boot delay and clear the known Nokia preboot setting using Configure Nokia UART first.'); + } + if (!Number.isSafeInteger(image.size) || image.size <= 0 || image.size > NOKIA_SLOT_SIZE || + image.slotSize !== NOKIA_SLOT_SIZE || image.kernelSize + 64 > 0x180000) { + throw problem('IMAGE_SIZE', 'The image does not fit the Nokia slot or the bootloader kernel read window.'); + } + return Object.freeze({ protectedSlot, targetSlot, offset: OFFSETS[targetSlot], + slotSize: NOKIA_SLOT_SIZE, bootMode, bootProfile: upgraded ? '19.07' : 'legacy', + migrateBootScripts: bootMode !== 'stage' && !upgraded, image: Object.freeze({ ...image }) }); +} + +async function inspectDevice(serial) { + const version = await serial.command('version'); + if (!normalize(version).split('\n').some(line => line.trim() === VERSION)) { + throw problem('BOOTLOADER', 'This bootloader version has not been validated for Nokia browser flashing. Nothing was written.'); + } + const settings = await readEnvironment(serial); + for (const command of ['loady', 'sf', 'crc32']) { + const response = await serial.command(`help ${command}`); + if (commandFailed(response) || !new RegExp(`\\b${command}\\b`).test(response)) { + throw problem('CAPABILITY', `The bootloader does not expose the required ${command} command.`); + } + } + const info = await serial.command('bdinfo'); + const start = /\bmemstart\s*=\s*(?:0x)?([0-9a-f]+)/i.exec(info); + const size = /\bmemsize\s*=\s*(?:0x)?([0-9a-f]+)/i.exec(info); + if (commandFailed(info) || !start || !size || parseInt(start[1], 16) !== 0x80000000 || + parseInt(size[1], 16) < 0x04000000) { + throw problem('MEMORY', 'Could not verify the Nokia RAM range for image transfer and readback.'); + } + const flash = await checked(serial, 'sf probe 0'); + if (!/\btotal\s+16\s+MiB\b/i.test(flash)) { + throw problem('FLASH_SIZE', 'The SPI flash was not identified as a 16 MiB device. Nothing was erased.'); + } + return settings; +} + +async function verifyCrc(serial, size, expected, timeoutMs) { + const response = await checked(serial, `crc32 ${hex(RAM)} ${hex(size)}`, timeoutMs); + const matches = [...response.matchAll(/CRC32\s+for\s+(?:0x)?([0-9a-f]+)\s*\.\.\.\s*(?:0x)?([0-9a-f]+)\s*==>\s*([0-9a-f]{8})\b/gi)]; + if (matches.length !== 1 || parseInt(matches[0][1], 16) !== RAM || + parseInt(matches[0][2], 16) !== RAM + size - 1 || matches[0][3].toLowerCase() !== expected) { + throw problem('CRC_MISMATCH', 'The device CRC32 does not match the expected bytes. No further writes will be made.'); + } +} + +async function loadIntoRam(serial, data, image, { signal, onProgress, transferTimeoutMs, commandTimeoutMs }) { + const readyDeadline = Date.now() + commandTimeoutMs; + await serial.write(`loady ${hex(RAM)}\r`, readyDeadline); + let banner = ''; + while (!banner.endsWith('\n')) { + if (banner.length > 4096) throw problem('YMODEM_READY', 'Unexpected output before the YMODEM receiver started.'); + banner += String.fromCharCode(await serial.readByte(readyDeadline, signal)); + if (banner.endsWith('\n') && !/Ready for binary \(ymodem\) download/i.test(banner)) banner = ''; + } + if (!/Ready for binary \(ymodem\) download to 0x80800000 at 115200 bps/i.test(banner)) { + throw problem('YMODEM_READY', 'The YMODEM receiver did not confirm the expected RAM address and baud rate.'); + } + await sendYmodem(serial, data, { signal, filename: 'nokia-firmware.image', + transferTimeoutMs, onProgress: sent => onProgress(sent, data.length) }); + const response = await serial.waitPrompt(Date.now() + commandTimeoutMs); + const size = /Total Size\s*=\s*0x([0-9a-f]+)\s*=\s*(\d+)\s+Bytes/i.exec(response); + if (commandFailed(response) || !size || parseInt(size[1], 16) !== data.length || Number(size[2]) !== data.length) { + throw problem('TRANSFER_SIZE', 'U-Boot did not confirm the exact received file size. Nothing was erased.'); + } + await verifyCrc(serial, image.size, image.crc32, commandTimeoutMs); +} + +/** + * Internal orchestration over a verified console and an inspected image. + * Kept separate for transcript tests; the browser entry point below always + * snapshots and validates the file before opening a serial port. + */ +export async function runNokiaFlashSession(serial, { data, metadata: image }, { + signal, bootMode = 'trial', onStatus = () => {}, onProgress = () => {}, + onPhase = () => {}, onBackup = () => {}, confirmFlash, + commandTimeoutMs = 10000, flashTimeoutMs = 180000, transferTimeoutMs = 30 * 60 * 1000 +} = {}) { + let phase = 'inspect'; + let flashStarted = false; + let activationStarted = false; + const status = (next, message) => { phase = next; onPhase(next); onStatus(message); }; + try { + if (data.length !== image.size || crc32Hex(data) !== image.crc32) throw problem('IMAGE_CHANGED', 'The inspected image bytes changed.'); + status('inspect', 'Checking the Nokia bootloader, flash layout and committed image.'); + const before = await inspectDevice(serial); + const plan = planNokiaFlash(before, image, bootMode); + const expectedSlot = new Uint8Array(NOKIA_SLOT_SIZE).fill(0xff); + expectedSlot.set(data); + const slotCrc = crc32Hex(expectedSlot); + await bounded(Promise.resolve(onBackup({ model: 'Nokia G-010S-A', + profile: VERSION, capturedAt: new Date().toISOString(), settings: { ...before }, + image: { ...image }, plan: { ...plan } })), undefined, signal); + status('review', `Review the image and slot ${plan.targetSlot}. Committed slot ${plan.protectedSlot} will be preserved.`); + checkAbort(signal); + if (typeof confirmFlash !== 'function' || + await bounded(Promise.resolve(confirmFlash(plan)), undefined, signal) !== true) throw cancelled(); + await serial.acquire(); + if (!sameEnvironment(before, await inspectDevice(serial))) { + throw problem('SETTINGS_CHANGED', 'The boot configuration changed during confirmation. Nothing was erased; reconnect and review the new state.'); + } + status('transfer', 'Sending the image to RAM over YMODEM at 115200 baud.'); + await loadIntoRam(serial, data, image, { signal, onProgress, transferTimeoutMs, commandTimeoutMs }); + // A several-minute transfer is not a reason to trust stale boot state. + if (!sameEnvironment(before, await readEnvironment(serial))) { + throw problem('SETTINGS_CHANGED', 'The boot configuration changed during transfer. Nothing was erased.'); + } + checkAbort(signal); + status('erase', `Erasing only slot ${plan.targetSlot}. Keep the module powered.`); + checkAbort(signal); + flashStarted = true; + await checked(serial, `sf erase ${hex(plan.offset)} ${hex(plan.slotSize)}`, flashTimeoutMs); + status('write', `Writing ${image.size} bytes to slot ${plan.targetSlot}. Keep the module powered.`); + await checked(serial, `sf write ${hex(RAM)} ${hex(plan.offset)} ${hex(image.size)}`, flashTimeoutMs); + status('verify', 'Reading the entire slot back, including its erased tail, and checking CRC32.'); + await checked(serial, `sf read ${hex(RAM)} ${hex(plan.offset)} ${hex(plan.slotSize)}`, flashTimeoutMs); + await verifyCrc(serial, plan.slotSize, slotCrc, flashTimeoutMs); + if (bootMode !== 'stage') { + status('activate', bootMode === 'trial' + ? 'Updating the supported boot scripts and saving a one-time trial. The previous image remains the default.' + : 'Updating the supported boot scripts and saving the verified image as the default.'); + if (!sameEnvironment(before, await readEnvironment(serial))) throw problem('SETTINGS_CHANGED', 'Boot settings changed before activation.'); + checkAbort(signal); + activationStarted = true; + // The legacy do_bootm hook increments/saves boot_fail and flips + // slots at its threshold. Use the exact image's migration, whose + // selector resets that counter before every normal boot. A single + // boot_fail=0 assignment would only postpone an unexpected flip. + const after = { ...before, ...NOKIA_UPGRADE_SETTINGS, + [`image${plan.targetSlot}_is_valid`]: '1', + committed_image: String(bootMode === 'commit' ? plan.targetSlot : plan.protectedSlot), + next_active: String(plan.targetSlot) }; + for (const key of ['boot_image', 'update_system', 'select_image', `image${plan.targetSlot}_is_valid`, + 'boot_fail', 'committed_image', 'next_active']) { + if (before[key] === after[key]) continue; + // All values come from the fixed inspected migration or a + // validated slot number. Quotes defer ${...} until boot time. + const value = after[key]; + if (!/^[\x20-\x7e]+$/.test(value) || /['\\]/.test(value)) throw problem('ENVIRONMENT', 'The migration value cannot be quoted safely.'); + await checked(serial, `setenv ${key} '${value}'`); + } + if (!sameEnvironment(after, await readEnvironment(serial))) throw problem('SETTINGS_CHANGED', 'The proposed boot settings did not read back correctly.'); + await checked(serial, 'saveenv', flashTimeoutMs); + } + status('success', bootMode === 'stage' + ? `Slot ${plan.targetSlot} verified. Boot selection is unchanged; the module remains at U-Boot.` + : `Slot ${plan.targetSlot} verified and ${bootMode === 'trial' ? 'selected for one trial' : 'saved as the default'}. Cold power-cycle the module, then check UART and network access. The previous firmware slot was not erased.`); + return Object.freeze({ protectedSlot: plan.protectedSlot, targetSlot: plan.targetSlot, + offset: plan.offset, size: image.size, sha256: image.sha256, bootMode, verified: true }); + } catch (error) { + if (activationStarted) { + throw problem('SAVE_UNCERTAIN', `The firmware slot passed readback verification, but its boot settings may not be saved (${error.message}). Keep power connected and inspect the console before rebooting. The original firmware slot was not erased.`); + } + if (flashStarted) { + throw problem('FLASH_UNCERTAIN', `Flashing stopped during ${phase} (${error.message}). The target slot may be incomplete. Keep power connected until any flash operation finishes, then inspect the console. The original committed slot was not erased and no new boot selection was saved.`); + } + throw error; + } +} + +/** Public browser entry point: no image-validation or device-profile bypass. */ +export async function flashNokiaFirmware(port, input, options = {}) { + const { signal, startupTimeoutMs = 45000, commandTimeoutMs = 10000, ioTimeoutMs = 5000, + flashTimeoutMs = 180000, transferTimeoutMs = 30 * 60 * 1000 } = options; + for (const value of [startupTimeoutMs, commandTimeoutMs, ioTimeoutMs, flashTimeoutMs, transferTimeoutMs]) { + if (!Number.isFinite(value) || value <= 0) throw new TypeError('Serial timeouts must be positive finite numbers.'); + } + checkAbort(signal); + const data = Uint8Array.from(input); + const metadata = await inspectNokiaImage(data); + checkAbort(signal); + const serial = new NokiaConsole(port, { signal, baudRate: 115200, startupTimeoutMs, commandTimeoutMs, ioTimeoutMs }); + try { + options.onPhase?.('connect'); + options.onStatus?.('Opening the serial port. Power-cycle the Nokia when prompted.'); + await serial.open(); + options.onStatus?.('Serial port open. Power-cycle the module now, or leave it at an existing FALCON prompt.'); + await serial.acquire(); + return await runNokiaFlashSession(serial, { data, metadata }, options); + } finally { + await serial.close(); + } +} diff --git a/.vitepress/theme/lib/nokiaImage.js b/.vitepress/theme/lib/nokiaImage.js new file mode 100644 index 00000000..65109f10 --- /dev/null +++ b/.vitepress/theme/lib/nokiaImage.js @@ -0,0 +1,138 @@ +// A legacy MIPS uImage/SquashFS header does not identify a G-010S-A image: +// the inspected Huawei and Alcatel images have the same kernel and generic +// "SFP" fwtool metadata. Only reviewed, complete-file digests are accepted. +export const NOKIA_SLOT_SIZE = 0x600000; + +const UIMAGE_HEADER_SIZE = 64; +const SQUASHFS_SUPERBLOCK_SIZE = 96; +const NO_TABLE = 0xffffffffffffffffn; +const IMAGES = Object.freeze({ + '5c0d6853645d72748cf844f9e64fc57c38924cc7938ef14a40a827015bbc1248': Object.freeze({ + profile: 'g010sa-19.07-20260814', + name: 'Nokia G-010S-A OpenWrt 19.07 (2026-08-14)', + size: 0x4400eb + }) +}); + +function failure(code, message) { + return Object.assign(new Error(message), { name: 'NokiaImageError', code }); +} + +const CRC_TABLE = new Uint32Array(256); +for (let byte = 0; byte < CRC_TABLE.length; byte++) { + let value = byte; + for (let bit = 0; bit < 8; bit++) value = (value >>> 1) ^ ((value & 1) ? 0xedb88320 : 0); + CRC_TABLE[byte] = value >>> 0; +} + +function crc32(bytes) { + let crc = 0xffffffff; + for (const byte of bytes) crc = (crc >>> 8) ^ CRC_TABLE[(crc ^ byte) & 0xff]; + return (crc ^ 0xffffffff) >>> 0; +} + +// U-Boot's crc32 command uses this CRC-32/ISO-HDLC representation. It checks +// transfer/readback integrity, while SHA-256 below identifies the image. +export function crc32Hex(bytes) { + if (!(bytes instanceof Uint8Array)) throw new TypeError('Expected a Uint8Array.'); + return crc32(bytes).toString(16).padStart(8, '0'); +} + +function inspectStructure(bytes) { + const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + if (view.getUint32(0, false) !== 0x27051956) { + throw failure('INVALID_UIMAGE', 'Select a supported Nokia firmware image, not a flash dump or an archive.'); + } + const header = bytes.slice(0, UIMAGE_HEADER_SIZE); + header.fill(0, 4, 8); + if (crc32(header) !== view.getUint32(4, false)) { + throw failure('BAD_HEADER_CRC', 'The uImage header checksum is invalid. The firmware file may be damaged.'); + } + // Linux, MIPS, kernel, LZMA; load/entry addresses of the reviewed profile. + if (view.getUint8(28) !== 5 || view.getUint8(29) !== 5 || + view.getUint8(30) !== 2 || view.getUint8(31) !== 3 || + view.getUint32(16, false) !== 0x80002000 || view.getUint32(20, false) !== 0x80002000) { + throw failure('UNSUPPORTED_UIMAGE', 'This is not the supported Nokia MIPS/LZMA kernel format.'); + } + const kernelSize = view.getUint32(12, false); + const rootfsOffset = UIMAGE_HEADER_SIZE + kernelSize; + if (kernelSize < 13 || rootfsOffset > bytes.length - SQUASHFS_SUPERBLOCK_SIZE) { + throw failure('INVALID_KERNEL_SIZE', 'The kernel length extends outside the firmware image.'); + } + if (crc32(bytes.subarray(UIMAGE_HEADER_SIZE, rootfsOffset)) !== view.getUint32(24, false)) { + throw failure('BAD_KERNEL_CRC', 'The kernel data checksum is invalid. The firmware file may be damaged.'); + } + const squashfs = new DataView(bytes.buffer, bytes.byteOffset + rootfsOffset, bytes.length - rootfsOffset); + if (squashfs.getUint32(0, true) !== 0x73717368 || + squashfs.getUint16(28, true) !== 4 || squashfs.getUint16(30, true) !== 0 || + squashfs.getUint16(20, true) !== 4) { + throw failure('INVALID_SQUASHFS', 'Expected a SquashFS 4.0/XZ root filesystem immediately after the kernel.'); + } + const blockSize = squashfs.getUint32(12, true); + const blockLog = squashfs.getUint16(22, true); + const rootfsSize64 = squashfs.getBigUint64(40, true); + if (!squashfs.getUint32(4, true) || !squashfs.getUint16(26, true) || + blockLog < 12 || blockLog > 20 || blockSize !== 2 ** blockLog || + rootfsSize64 < BigInt(SQUASHFS_SUPERBLOCK_SIZE) || + rootfsSize64 > BigInt(bytes.length - rootfsOffset)) { + throw failure('INVALID_SQUASHFS', 'The root filesystem has invalid sizes or extends outside the image.'); + } + const table = (offset, optional = false) => { + const value = squashfs.getBigUint64(offset, true); + if (optional && value === NO_TABLE) return value; + if (value < BigInt(SQUASHFS_SUPERBLOCK_SIZE) || value >= rootfsSize64) { + throw failure('INVALID_SQUASHFS', 'A root filesystem table points outside the image.'); + } + return value; + }; + const idTable = table(48); + table(56, true); + const inodeTable = table(64); + const directoryTable = table(72); + table(80, squashfs.getUint32(16, true) === 0); + table(88, true); + const rootInode = squashfs.getBigUint64(32, true); + if (inodeTable >= directoryTable || directoryTable >= idTable || + idTable + 8n > rootfsSize64 || (rootInode & 0xffffn) >= 8192n || + inodeTable + (rootInode >> 16n) >= directoryTable) { + throw failure('INVALID_SQUASHFS', 'The root filesystem metadata bounds are invalid.'); + } + return { kernelSize, rootfsOffset, rootfsSize: Number(rootfsSize64) }; +} + +/** + * Validate the complete file before opening a serial port. No filename, model + * checkbox, or generic uImage/fwtool header can override the digest allowlist. + * Callers that later transmit bytes must keep their own private input snapshot. + */ +export async function inspectNokiaImage(input) { + if (!(input instanceof Uint8Array)) { + throw failure('INVALID_IMAGE', 'Firmware must be supplied as a Uint8Array.'); + } + if (input.length > NOKIA_SLOT_SIZE) { + throw failure('IMAGE_TOO_LARGE', 'The file exceeds a 6 MiB Nokia firmware slot. Full flash dumps are not supported.'); + } + if (input.length < UIMAGE_HEADER_SIZE + SQUASHFS_SUPERBLOCK_SIZE) { + throw failure('INVALID_IMAGE', 'The firmware file is empty or truncated.'); + } + // Uint8Array.from also copies Node Buffers; Buffer.slice would alias input. + const bytes = Uint8Array.from(input); + const structure = inspectStructure(bytes); + if (!globalThis.crypto?.subtle) { + throw failure('CRYPTO_UNAVAILABLE', 'SHA-256 verification requires a browser with Web Crypto on HTTPS.'); + } + const digest = new Uint8Array(await globalThis.crypto.subtle.digest('SHA-256', bytes)); + const sha256 = Array.from(digest, byte => byte.toString(16).padStart(2, '0')).join(''); + const profile = Object.hasOwn(IMAGES, sha256) ? IMAGES[sha256] : null; + if (!profile || profile.size !== bytes.length) { + throw failure('UNSUPPORTED_IMAGE', 'This file is not a reviewed Nokia G-010S-A firmware image. Huawei, Alcatel, raw partition backups and modified images are rejected.'); + } + return Object.freeze({ + ...profile, + size: bytes.length, + sha256, + crc32: crc32Hex(bytes), + ...structure, + slotSize: NOKIA_SLOT_SIZE + }); +} diff --git a/.vitepress/theme/lib/nokiaSerial.js b/.vitepress/theme/lib/nokiaSerial.js index 65c8a63a..2bce1216 100644 --- a/.vitepress/theme/lib/nokiaSerial.js +++ b/.vitepress/theme/lib/nokiaSerial.js @@ -1,215 +1,7 @@ -// Nokia G-010S-A console settings only. This procedure never flashes firmware, -// applies Huawei GPIO settings, or treats BootROM output as a command prompt. -const PROMPT = /(?:^|\n)[ \t]*FALCON[ \t]*=>[ \t]*$/; -const ROM = /(?:^|\n)[ \t]*ROM:/; -const STARTUP = /(?:^|\n)[ \t]*(?:U-Boot\b|Chip:|Bootmode:|Reset cause:|CPU Clock:|Press SPACE|Hit any key|Autoboot)/; -const STARTUP_EVENTS = /(?:^|\n)[ \t]*(?:ROM:[ \t]*V|U-Boot\b|Chip:|Bootmode:|Reset cause:|CPU Clock:|Press SPACE|Hit any key|Autoboot)/g; -const LINUX = /(?:^|\n)[ \t]*(?:Starting kernel|Linux version |BusyBox |[^\n]*[Ll]ogin:[ \t]*$|root@[^\n]*[#$][ \t]*$)/m; -const RECOVERABLE = new Set(['BreakError', 'FramingError', 'ParityError']); -const VARIABLES = ['asc0', 'bootdelay', 'preboot']; -const MAX_OUTPUT = 256 * 1024; - -function failure(code, message) { - return Object.assign(new Error(message), { name: 'NokiaSerialError', code }); -} - -function cancelled() { - return new DOMException('The Nokia UART procedure was cancelled.', 'AbortError'); -} - -function checkAbort(signal) { - if (signal?.aborted) throw cancelled(); -} - -// A timed-out read remains owned by the session until it is consumed or closed. -// This avoids concurrent readers and losing bytes between polling intervals. -async function bounded(promise, ms, signal, error) { - if (signal?.aborted) { - // The caller may already have started an I/O request when abort fires. - // Observe a late rejection even though this operation cannot continue. - Promise.resolve(promise).catch(() => {}); - throw cancelled(); - } - let timer; - let abort; - const interrupted = new Promise((_, reject) => { - if (ms !== undefined) timer = setTimeout(() => reject(error), Math.max(0, ms)); - abort = () => reject(cancelled()); - signal?.addEventListener('abort', abort, { once: true }); - }); - try { - return await Promise.race([promise, interrupted]); - } finally { - clearTimeout(timer); - signal?.removeEventListener('abort', abort); - } -} - -function normalize(text) { - return text.replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, '').replace(/\r\n?/g, '\n'); -} - -function checkConsole(text, command = false) { - if (/ROM:\s*Boot\?|Boot\?\s*\(0-9A-F/i.test(text)) { - throw failure('BOOTROM_MENU', 'The module is at the BootROM recovery menu, not the FALCON U-Boot console. Use the documented Nokia recovery procedure.'); - } - if (LINUX.test(text)) { - throw failure('LINUX_CONSOLE', 'The module has booted into Linux. Use SSH to enable UART, or power-cycle the module and retry to stop U-Boot.'); - } - if (command && (ROM.test(text) || STARTUP.test(text))) { - throw failure('DISCONNECTED', 'The module restarted during the command. No further commands will be sent.'); - } -} - -class NokiaConsole { - constructor(port, { signal, baudRate, startupTimeoutMs, commandTimeoutMs, ioTimeoutMs }) { - Object.assign(this, { port, signal, baudRate, startupTimeoutMs, commandTimeoutMs, ioTimeoutMs }); - this.buffer = ''; - this.decoder = new TextDecoder(); - this.encoder = new TextEncoder(); - this.verified = false; - this.readErrors = 0; - } - - async open() { - checkAbort(this.signal); - this.opening = this.port.open({ baudRate: this.baudRate, dataBits: 8, stopBits: 1, parity: 'none', flowControl: 'none' }); - await bounded(this.opening, this.ioTimeoutMs, this.signal, failure('TIMEOUT', 'Opening the serial port timed out.')); - this.opened = true; - this.reader = this.port.readable?.getReader(); - this.writer = this.port.writable?.getWriter(); - if (!this.reader || !this.writer) throw failure('DISCONNECTED', 'The serial port has no readable/writable connection.'); - } - - async write(text, deadline) { - checkAbort(this.signal); - if (!this.writer) throw failure('DISCONNECTED', 'The serial connection is closed.'); - const remaining = Math.min(this.ioTimeoutMs, deadline - Date.now()); - if (remaining <= 0) throw failure('TIMEOUT', 'The serial operation timed out.'); - try { - await bounded(this.writer.write(this.encoder.encode(text)), remaining, this.signal, - failure('TIMEOUT', 'Writing to the serial port timed out.')); - } catch (error) { - if (error.name === 'AbortError' || error.code) throw error; - throw failure('DISCONNECTED', `Could not write to the serial port: ${error.message}`); - } - } +// Configure the Nokia G-010S-A UART without flashing firmware. +import { NokiaConsole, failure, cancelled, checkAbort, bounded, normalize, commandFailed } from './nokiaConsole.js'; - async read(deadline, pollMs = Infinity) { - checkAbort(this.signal); - if (!this.pendingRead) this.pendingRead = this.reader.read(); - let result; - try { - result = await bounded(this.pendingRead, Math.min(pollMs, deadline - Date.now()), this.signal, - failure('POLL', 'Waiting for serial data.')); - } catch (error) { - if (error.code === 'POLL') return false; - this.pendingRead = undefined; - // Web Serial replaces its readable stream after these nonfatal - // errors (FTDI adapters can report BREAK during module insertion). - if (RECOVERABLE.has(error.name) && ++this.readErrors <= 5) { - this.reader.releaseLock(); - this.reader = this.port.readable?.getReader(); - this.decoder = new TextDecoder(); - if (this.reader) return true; - } - if (error.name === 'AbortError') throw error; - throw failure('DISCONNECTED', `Serial reading failed (${error.name}): ${error.message}. Check the adapter, wiring and 115200 8-N-1 settings.`); - } - this.pendingRead = undefined; - if (result.done) throw failure('DISCONNECTED', 'The serial connection closed before the procedure completed.'); - this.buffer += this.decoder.decode(result.value, { stream: true }); - if (this.buffer.length > MAX_OUTPUT) throw failure('TIMEOUT', 'Too much serial output was received without a FALCON prompt.'); - return true; - } - - async acquire() { - this.verified = false; - const deadline = Date.now() + this.startupTimeoutMs; - await this.write('\r', deadline); // Also elicit a prompt from an idle U-Boot. - let lastEvent = -1; - let interruptUntil = 0; - let nextInterrupt = 0; - while (Date.now() < deadline) { - checkAbort(this.signal); - const text = normalize(this.buffer); - checkConsole(text); - if (PROMPT.test(text)) { - this.buffer = ''; - const bytes = crypto.getRandomValues(new Uint8Array(12)); - const nonce = '__NOKIA_UART_' + Array.from(bytes, b => b.toString(16).padStart(2, '0')).join('') + '__'; - const response = await this.exchange(`echo ${nonce}`, Math.min(deadline, Date.now() + this.commandTimeoutMs)); - if (!normalize(response).split('\n').some(line => line.trim() === nonce)) { - throw failure('UNVERIFIED', 'The FALCON prompt did not return the console verification response. No settings were changed.'); - } - this.verified = true; - return; - } - const events = Array.from(text.matchAll(STARTUP_EVENTS)); - const latest = events.at(-1)?.index ?? -1; - if (latest > lastEvent) { - lastEvent = latest; - interruptUntil = Math.min(deadline, Date.now() + 5000); - nextInterrupt = Date.now(); - } - if (Date.now() < interruptUntil && Date.now() >= nextInterrupt) { - await this.write('\x03', deadline); - nextInterrupt = Date.now() + 50; - } - await this.read(deadline, Date.now() < interruptUntil ? Math.max(1, nextInterrupt - Date.now()) : Infinity); - } - const text = normalize(this.buffer); - if (ROM.test(text) && !STARTUP.test(text)) { - throw failure('ROM_ONLY', 'Only BootROM output was received; an interactive U-Boot prompt was not obtained. The UART console may be disabled by asc0=3. Enable it through SSH or the supported web interface, or use the documented Nokia recovery procedure if network access is unavailable. No settings were changed.'); - } - throw failure('TIMEOUT', 'Timed out waiting for a verified FALCON prompt. Check the Nokia pinout and power-cycle the module after starting this procedure. No settings were changed.'); - } - - async exchange(command, deadline) { - await this.write(command + '\r', deadline); - while (Date.now() < deadline) { - await this.read(deadline); - const text = normalize(this.buffer); - checkConsole(text, true); - const prompt = PROMPT.exec(text); - if (prompt) { - this.buffer = ''; - return text.slice(0, prompt.index); - } - } - throw failure('TIMEOUT', `U-Boot did not finish the ${command.split(' ')[0]} command in time. No further commands will be sent.`); - } - - async command(command) { - if (!this.verified) throw failure('UNVERIFIED', 'A verified FALCON console is required before sending commands.'); - try { - return await this.exchange(command, Date.now() + this.commandTimeoutMs); - } catch (error) { - this.verified = false; - throw error; - } - } - - async close() { - this.verified = false; - if (!this.opened) { - // An open request may finish after its timeout or user cancellation. - this.opening?.then(() => this.port.close()).catch(() => {}); - return; - } - const limit = Math.min(1000, this.ioTimeoutMs); - const cleanup = promise => bounded(Promise.resolve(promise).catch(() => {}), limit, undefined, - failure('TIMEOUT', 'Serial cleanup timed out.')).catch(() => {}); - await Promise.all([cleanup(this.reader?.cancel()), cleanup(this.writer?.abort())]); - try { this.reader?.releaseLock(); } catch { /* A disconnected stream can already be released. */ } - try { this.writer?.releaseLock(); } catch { /* A disconnected stream can already be released. */ } - await cleanup(this.port.close()); - } -} - -function commandFailed(response) { - return /\b(?:error|failed|failure|bad crc|unknown command|timeout|timed out)\b|^\s*Usage:/im.test(response); -} +const VARIABLES = ['asc0', 'bootdelay', 'preboot']; async function readSettings(serial) { const settings = {}; diff --git a/.vitepress/theme/lib/ymodem.js b/.vitepress/theme/lib/ymodem.js new file mode 100644 index 00000000..7c23da7c --- /dev/null +++ b/.vitepress/theme/lib/ymodem.js @@ -0,0 +1,206 @@ +// YMODEM/CRC sender for a receiver already started with U-Boot's `loady`. +// Keep this separate from the historical Huawei XYMini implementation. +// Receiver reference: https://github.com/u-boot/u-boot/blob/v2015.04/common/xyzModem.c +const SOH = 0x01; +const STX = 0x02; +const EOT = 0x04; +const ACK = 0x06; +const NAK = 0x15; +const CAN = 0x18; +const CRC = 0x43; +const DATA_SIZE = 1024; + +function failure(code, message) { + return Object.assign(new Error(message), { name: 'YmodemError', code }); +} + +function checkAbort(signal) { + if (signal?.aborted) throw new DOMException('Firmware transfer cancelled.', 'AbortError'); +} + +function isTimeout(error) { + return ['TIMEOUT', 'POLL', 'YMODEM_TIMEOUT'].includes(error?.code) || error?.name === 'TimeoutError'; +} + +function crc16(bytes) { + let crc = 0; + for (const byte of bytes) { + crc ^= byte << 8; + for (let bit = 0; bit < 8; bit++) { + crc = ((crc << 1) ^ ((crc & 0x8000) ? 0x1021 : 0)) & 0xffff; + } + } + return crc; +} + +function packet(sequence, bytes, size, padding = 0) { + const result = new Uint8Array(size + 5); + result[0] = size === 128 ? SOH : STX; + result[1] = sequence & 0xff; + result[2] = result[1] ^ 0xff; + result.fill(padding, 3, 3 + size); + result.set(bytes, 3); + const checksum = crc16(result.subarray(3, 3 + size)); + result[3 + size] = checksum >>> 8; + result[4 + size] = checksum & 0xff; + return result; +} + +/** + * Transfer one file, including the size header and final empty batch header. + * + * The caller must first verify U-Boot's loady readiness banner. Its transport + * supplies readByte(deadline, signal) and writeBytes(bytes, deadline, signal). + * Deadlines are absolute Date.now() values. Both methods must honour deadlines + * and aborts; a read timeout must not consume a later byte. The transport owns + * the byte queue, so bytes after the final ACK remain available to the caller's + * console parser, even when ACK and the U-Boot prompt arrive in one USB chunk. + * + * A completed transfer is not permission to flash: the caller must separately + * verify the reported length and a checksum of the entire RAM buffer. + */ +export async function sendYmodem(io, data, { + signal, + filename = 'firmware.image', + onProgress = () => {}, + startupTimeoutMs = 30000, + responseTimeoutMs = 5000, + writeTimeoutMs = 5000, + transferTimeoutMs = 30 * 60 * 1000, + maxRetries = 10 +} = {}) { + if (!(data instanceof Uint8Array) || data.length === 0) { + throw failure('YMODEM_INPUT', 'Select a nonempty binary firmware image.'); + } + if (typeof io?.readByte !== 'function' || typeof io?.writeBytes !== 'function') { + throw failure('YMODEM_INPUT', 'The transfer requires a bounded byte transport.'); + } + // The filename is metadata, never a terminal command or a local path. + if (typeof filename !== 'string' || !/^[A-Za-z0-9._-]{1,96}$/.test(filename)) { + throw failure('YMODEM_INPUT', 'Use a short ASCII filename without paths or control characters.'); + } + const timing = [startupTimeoutMs, responseTimeoutMs, writeTimeoutMs, transferTimeoutMs]; + if (!timing.every(value => Number.isFinite(value) && value > 0) || + !Number.isInteger(maxRetries) || maxRetries < 0 || maxRetries > 100) { + throw failure('YMODEM_INPUT', 'Invalid transfer timeout or retry limit.'); + } + checkAbort(signal); + + const expires = Date.now() + transferTimeoutMs; + let retries = 0; + let started = false; + const deadline = ms => Math.min(expires, Date.now() + ms); + + function checkTime(end) { + checkAbort(signal); + if (Date.now() >= end) throw failure('YMODEM_TIMEOUT', 'The firmware transfer timed out.'); + } + + async function write(bytes) { + const end = deadline(writeTimeoutMs); + checkTime(end); + await io.writeBytes(bytes, end, signal); + checkTime(expires); + } + + async function control(accepted, end) { + let cancellations = 0; + let ignored = 0; + while (true) { + checkTime(end); + const byte = await io.readByte(end, signal); + checkTime(expires); + if (!Number.isInteger(byte) || byte < 0 || byte > 255) { + throw failure('YMODEM_IO', 'The serial connection did not return a valid byte.'); + } + if (byte === CAN) { + if (++cancellations >= 2) { + throw failure('YMODEM_CANCELLED', 'The receiver cancelled the firmware transfer.'); + } + } else { + cancellations = 0; + if (accepted.includes(byte)) return byte; + } + // Repeated C characters and harmless status text must not extend + // a deadline or keep an immediate/noisy reader spinning forever. + if (++ignored > 4096) { + throw failure('YMODEM_PROTOCOL', 'Too much unexpected serial data during the transfer.'); + } + } + } + + async function sendPacket(bytes, label) { + for (let attempt = 0; attempt <= maxRetries; attempt++) { + checkTime(expires); + await write(bytes); + try { + const answer = await control([ACK, NAK], deadline(responseTimeoutMs)); + if (answer === ACK) return; + } catch (error) { + if (!isTimeout(error)) throw error; + checkTime(expires); + } + if (attempt < maxRetries) retries++; + } + throw failure('YMODEM_RETRIES', `The receiver did not acknowledge ${label}; the retry limit was reached.`); + } + + async function endFile() { + // Standard receivers can NAK the first EOT; U-Boot can ACK it twice. + // C alone also establishes that the receiver is waiting for the final + // batch header when an EOT acknowledgement was lost. + for (let attempt = 0; attempt <= maxRetries; attempt++) { + await write(Uint8Array.of(EOT)); + let answer; + try { + answer = await control([ACK, NAK, CRC], deadline(responseTimeoutMs)); + } catch (error) { + if (!isTimeout(error)) throw error; + checkTime(expires); + } + if (answer === CRC) return; + if (answer === ACK) { + await control([CRC], deadline(responseTimeoutMs)); + return; + } + if (attempt < maxRetries) retries++; + } + throw failure('YMODEM_RETRIES', 'The receiver did not finish the file transfer.'); + } + + try { + started = true; + const ready = await control([CRC, NAK], deadline(startupTimeoutMs)); + if (ready !== CRC) { + throw failure('YMODEM_CHECKSUM', 'The receiver requested legacy checksum mode; CRC YMODEM is required.'); + } + const metadata = new TextEncoder().encode(`${filename}\0${data.length}\0`); + await sendPacket(packet(0, metadata, 128), 'the file header'); + + // U-Boot 2011.12 and 2015.04 do not necessarily send another C after + // acknowledging block 0. Start data after ACK; an optional C is ignored + // while waiting for that data block's ACK. Retry only after NAK/timeout, + // avoiding duplicate packets when C and ACK arrive in separate chunks. + let sequence = 1; + for (let offset = 0; offset < data.length; offset += DATA_SIZE) { + const end = Math.min(offset + DATA_SIZE, data.length); + await sendPacket(packet(sequence, data.subarray(offset, end), DATA_SIZE, 0x1a), `data block ${sequence}`); + sequence = (sequence + 1) & 0xff; + onProgress(end, data.length); + } + + await endFile(); + await sendPacket(packet(0, new Uint8Array(0), 128), 'the final batch header'); + return { bytesSent: data.length, retries }; + } catch (error) { + if (started) { + // Cancellation has to reach loady even when the operation's signal + // is already aborted. Do not let cleanup replace the original error. + try { + await io.writeBytes(Uint8Array.of(CAN, CAN, CAN, CAN, 0x08, 0x08, 0x08, 0x08), + Date.now() + Math.min(writeTimeoutMs, 1000), new AbortController().signal); + } catch {} + } + throw error; + } +} diff --git a/ont/ont-huawei-ma5671a-ymodem.md b/ont/ont-huawei-ma5671a-ymodem.md index 18215cf1..d7d21eda 100644 --- a/ont/ont-huawei-ma5671a-ymodem.md +++ b/ont/ont-huawei-ma5671a-ymodem.md @@ -6,4 +6,8 @@ parent: Huawei MA5671A This procedure flashes the firmware on the stick via serial. Some of the firmwares that can be flashed are listed on the [Huawei MA5671A page](/ont-huawei-ma5671a). +::: warning Nokia G-010S-A uses a different flash layout +For G-010S-A, use the dedicated [Nokia Web Serial firmware flasher](/ont-nokia-g-010s-a-ymodem). The Huawei procedure's second slot starts at `0x800000` and extends to the end of flash; those addresses overlap Nokia's configuration and identity partitions. Selecting a Nokia image does not change this procedure's flash layout. +::: + diff --git a/ont/ont-nokia-g-010s-a-ymodem.md b/ont/ont-nokia-g-010s-a-ymodem.md new file mode 100644 index 00000000..6a1e7271 --- /dev/null +++ b/ont/ont-nokia-g-010s-a-ymodem.md @@ -0,0 +1,84 @@ +--- +title: Flash Nokia G-010S-A firmware through Web Serial +has_children: false +parent: Nokia G-010S-A +--- + +# Nokia G-010S-A Web Serial firmware flash + +This tool transfers a supported Nokia firmware image over UART using YMODEM. It writes the slot opposite the committed image and verifies the complete slot before changing any boot selection. It runs locally in your browser; the selected image and boot-settings backup are not uploaded to a server. + +::: warning Hardware validation +This implementation has automated protocol and failure-path tests and was checked against firmware binaries and a matching public U-Boot image. End-to-end validation on physical G-010S-A hardware is still pending. Keep a complete backup and an available UART recovery connection before using it. +::: + +## Before starting + +1. Make a complete backup of your own module, including U-Boot, its environment and the configuration/identity partitions. The JSON settings download offered here is **not** a full-flash backup. MTD exports such as `linux`, `rootfs` and `rootfs_data` overlap; do not concatenate every exported MTD file into a flash image. +2. [Enable UART](/ont-nokia-g-010s-a#enabling-serial) while SSH or the web interface is still available. This tool requires `asc0=0`, a positive boot delay, a cleared `preboot`, and a working `FALCON =>` prompt. Receiving only the three BootROM lines is insufficient. +3. Use the [Nokia pinout](/ont-nokia-g-010s-a#serial), 3.3 V TTL signalling and stable module power. Close any terminal using the adapter. The transfer uses **115200 8-N-1**, with no baud-rate switching. +4. Select the supported image below, connect the adapter, then power-cycle the module when prompted. Review the automatically selected target slot and download the original boot settings before confirming the write. + +## Supported image and bootloader + +The initial supported image is `nokia-g010sa_new_busybox_kernel_19.07-squashfs.image`, the inspected 2026-08-14 Nokia build: + +| Property | Value | +| --- | --- | +| File length | 4,456,683 bytes (`0x4400eb`) | +| SHA-256 | `5c0d6853645d72748cf844f9e64fc57c38924cc7938ef14a40a827015bbc1248` | +| Whole-file CRC32 | `cc6273fe` | +| U-Boot | `2015.04-lantiq-gpon-1.3.6.1 (Feb 07 2018 - 17:12:06)` with the inspected Nokia boot scripts | +| Flash | 16 MiB | + +The filename does not establish compatibility. The complete-file SHA-256 must match a reviewed image, and the tool also checks the kernel header/data CRCs and root-filesystem bounds. The corresponding Huawei and Alcatel builds have the **same kernel and generic `SFP` image metadata**, but different root filesystems. They are rejected even if renamed. Full dumps, arbitrary partition backups and modified files are also rejected. + +The boot configuration must match either the inspected legacy Nokia selector (`commit`) or that image's known upgraded selector (`committed_image`). Different layouts, custom boot scripts and pending trial boots are rejected. The saved `c_img` value is not used to guess the active slot. + + + +## What will be written + +| Region | Offset | Length | Tool behaviour | +| --- | --- | --- | --- | +| U-Boot | `0x000000` | `0x040000` | Preserved | +| U-Boot environment | `0x040000` | `0x080000` | Saved only when selecting a trial or a new default | +| Image 0 | `0x0c0000` | `0x600000` | Written only if image 1 is committed | +| Image 1 | `0x6c0000` | `0x600000` | Written only if image 0 is committed | +| Configuration and identity | `0xcc0000`–`0xffffff` | `0x340000` | Preserved by the tool | + +Before erasing anything, the receiver must report the exact file size and its RAM CRC32 must match. The selected 6 MiB slot is then erased completely, only the file's actual bytes are written, and the **whole slot** is read back and checked, including the unused tail which must remain erased. This avoids writing uninitialised RAM or retaining an old overlay after the firmware image. + +The firmware's own first-boot behaviour can still change its configuration. Preserving these flash regions during transfer is not a guarantee that every previous setting will carry over to the new firmware. + +## Choosing how to boot + +- **Keep the current boot choice:** upload and verify the other slot. No environment variables are saved and no boot scripts are migrated. +- **Try the new image on the next boot:** apply the inspected boot-script migration, retain the previous image as the committed default, and schedule one trial of the new image. The selector returns the persistent default to the previous slot before starting the trial. +- **Use the new image as the default:** apply the same migration and commit the verified target slot. The previous firmware contents remain in the other slot. + +The migration is part of the supplied Nokia image's `/lib/upgrade/common.sh`. It normally runs during Linux `sysupgrade`, **not automatically on first boot after a raw UART write**. It changes the selector to `committed_image` and resets `boot_fail` during each normal boot. The inspected loader otherwise increments this counter in `bootm` and can switch slots at its failure threshold. Clearing the counter just once does not replace the migration. + +All proposed boot settings are read back before `saveenv`; the tool requires a fresh command-success marker from the save. It never automatically resets the module or starts the kernel. After success, **cold power-cycle** the module rather than issuing a warm `reset`: the selector also recognises warm-reset image requests in scratch registers. Allow about one minute for the first startup, then check UART, network access and your GPON configuration. + +## Interrupted operations + +Closing the dialog or pressing Stop prevents further commands. A command already sent to the device cannot be undone. An interruption during erase/write leaves the target slot uncertain; an interruption during `saveenv` leaves the saved boot state uncertain. Keep power connected until any flash operation finishes and inspect the console before rebooting. The result remains visible after the dialog is closed. + +If an unknown layout, image or boot script is reported, collect the bootloader version and a sanitised environment report for review. Do not bypass the checks by renaming files or copying the Huawei erase/write commands. + +## Technical references + +The public comparison covered a complete 16 MiB Alcatel G-010S-P SPI dump, rooted Huawei firmware-partition dumps, and Nokia firmware partitions, bootloader binaries and environment transcripts. An independent complete Huawei or Nokia SPI dump was not validated. These artifacts corroborate the formats, flash layouts and boot scripts; they do not replace a physical flashing test. + +The published Nokia 2018 bootloader is byte-for-byte identical to the supplied Nokia U-Boot partition. The inspected legacy `select_image` script also exactly matches wteiken's owner-uploaded environment, including whitespace. The separate [codekow environment transcript](https://github.com/codekow/G-010S-AP/blob/65c7b2a72de79b8450702bf6cd74240a48434955/convert/G-010S-A.env.txt) contains a different selector variant and is not the source of that exact match. + +- [Nokia serial recovery and image-slot addresses](https://github.com/wteiken/G-010S-A/blob/980a6ca29de6eccf829324a6bb671eec1323cb36/unbricking.md) +- [Matching Nokia 2018 U-Boot partition](https://github.com/codekow/G-010S-AP/blob/65c7b2a72de79b8450702bf6cd74240a48434955/bootloader/1.3.6.1-2018.bin), SHA-256 `c6c461ede9f5d9f3fd8117452a0e9c97e01bb29be40a9e4a2df4e9d39216a837` +- [Primary owner environment and attachment](https://github.com/hwti/G-010S-A/issues/27#issuecomment-1324209958) +- [Alcatel G-010S-P full SPI dump](https://github.com/minhng99/alcatel_lucent-lantiq_falcon/blob/ea3bbb1bf23df3c5b0b2abc37cf371d35bbfd909/dump_alcatel_128s0.bin) +- [Huawei rooted firmware-partition images](https://github.com/Noltari/ma5671a-firmware/tree/22ec8c076081a5f506c565d95dc3af1602693f5e/huawei) +- [Nokia BGCB22 firmware-partition image](https://github.com/wteiken/G-010S-A/blob/980a6ca29de6eccf829324a6bb671eec1323cb36/firmwares/3FE46398BGCB22.bin) +- [Nokia firmware and upgrade behaviour](https://github.com/hwti/G-010S-A) +- [U-Boot 2015.04 YMODEM receiver](https://github.com/u-boot/u-boot/blob/v2015.04/common/xyzModem.c) +- [U-Boot 2015.04 serial load command](https://github.com/u-boot/u-boot/blob/v2015.04/common/cmd_load.c) diff --git a/ont/ont-nokia-g-010s-a.md b/ont/ont-nokia-g-010s-a.md index 77896417..5685ba0f 100644 --- a/ont/ont-nokia-g-010s-a.md +++ b/ont/ont-nokia-g-010s-a.md @@ -120,6 +120,12 @@ This helper cannot enable a console that never accepts U-Boot commands. It stops The [documented Nokia boot transcript](https://github.com/wteiken/G-010S-A/blob/main/unbricking.md#connecting-to-the-console) illustrates why a `U-Boot` banner alone is not a suitable trigger. The Huawei MA5671A web-root procedure uses different GPIO and Linux-shell steps and should not be used for G-010S-A. +## Flashing firmware through the browser + +The [Nokia Web Serial firmware flasher](/ont-nokia-g-010s-a-ymodem) can upload a reviewed G-010S-A image over YMODEM, verify it in RAM, write the slot opposite the committed image, and verify the complete slot after writing. It supports staging, a trial boot, or selecting the new firmware as the default, with the inspected image's required boot-script migration. + +It requires an interactive UART console and a supported bootloader configuration. Read the supported-image list and backup requirements on that page first. The Huawei flasher uses different slot sizes, addresses and boot-selection settings. + # GPON ONU status ## Getting the operational status of the ONU diff --git a/tests/nokiaFirmware.test.js b/tests/nokiaFirmware.test.js new file mode 100644 index 00000000..2a1e55a1 --- /dev/null +++ b/tests/nokiaFirmware.test.js @@ -0,0 +1,818 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { crc32Hex } from '../.vitepress/theme/lib/nokiaImage.js'; +import { + NOKIA_BOOT_PROFILE, NOKIA_UPGRADE_SETTINGS, + planNokiaFlash, runNokiaFlashSession, flashNokiaFirmware +} from '../.vitepress/theme/lib/nokiaFirmware.js'; +import { NokiaConsole } from '../.vitepress/theme/lib/nokiaConsole.js'; +import { sendYmodem } from '../.vitepress/theme/lib/ymodem.js'; + +const RAM = 0x80800000; +const SLOT_OFFSETS = [0x0c0000, 0x6c0000]; +const encoder = new TextEncoder(); +const decoder = new TextDecoder(); +const ACK = 0x06; +const CRC_REQUEST = 0x43; + +function fixtureImage() { + // Synthetic bytes exercise transport and write boundaries. Public entry + // point image identification is tested separately, without private dumps. + const data = Uint8Array.from({ length: 2051 }, (_, n) => (n * 37 + 11) & 0xff); + return { data, metadata: { + size: data.length, kernelSize: 1024, slotSize: 0x600000, + crc32: crc32Hex(data), sha256: 'a'.repeat(64), model: 'Nokia G-010S-A' + } }; +} + +function settings(overrides = {}) { + return { + ...NOKIA_BOOT_PROFILE, + update_system: 'run update_image0 && setenv commit 0 && setenv image0_is_valid 1 && saveenv', + commit: '0', next_active: '0', c_img: '1', + image0_is_valid: '1', image1_is_valid: '0', boot_fail: '2', + asc0: '0', bootdelay: '5', preboot: null, + ...overrides + }; +} + +function crc16(bytes) { + let crc = 0; + for (const value of bytes) { + crc ^= value << 8; + for (let bit = 0; bit < 8; bit++) crc = (crc << 1 ^ (crc & 0x8000 ? 0x1021 : 0)) & 0xffff; + } + return crc; +} + +// A deterministic U-Boot command/byte transcript, not a stub of sendYmodem. +// The real sender must perform its filename, data, EOT and final-header +// exchanges; only received bytes become the emulated RAM image. +class FakeFalcon { + constructor(options = {}) { + this.options = options; + this.environment = settings(options.environment); + this.persisted = { ...this.environment }; + this.originalProtectedSlot = Number(this.environment.select_image.includes('$committed_image') + ? this.environment.committed_image : this.environment.commit); + this.commands = []; + this.events = []; + this.bytes = []; + this.blocks = []; + this.receiverState = 'idle'; + this.nextSequence = 1; + this.acquisitions = 0; + this.saves = 0; + this.crcCalls = 0; + this.environmentReads = 0; + this.signal = options.signal; + } + + checkAbort() { + if (this.signal?.aborted) throw new DOMException('Cancelled', 'AbortError'); + } + + async acquire() { + this.checkAbort(); + this.acquisitions++; + this.events.push('acquire'); + } + + storage() { + this.flash ??= new Uint8Array(0x1000000).fill(0x5a); + return this.flash; + } + + async command(raw) { + this.checkAbort(); + this.commands.push(raw); + const match = /^(.*) && echo (__NOKIA_FLASH_[a-f0-9]+__)$/.exec(raw); + const command = match ? match[1] : raw; + const marker = match?.[2]; + this.events.push(command); + const intercept = await this.options.onCommand?.(command, this, raw); + if (intercept !== undefined) return intercept; + let response; + if (command === 'version') { + response = this.options.version ?? 'U-Boot 2015.04-lantiq-gpon-1.3.6.1 (Feb 07 2018 - 17:12:06)'; + } else if (command.startsWith('printenv ')) { + const key = command.slice(9); + if (key === 'bootcmd') this.environmentReads++; + const value = this.environment[key]; + response = value === null || value === undefined + ? `## Error: "${key}" not defined` + : `${key}=${value}`; + } else if (command.startsWith('help ')) { + const key = command.slice(5); + response = this.options.missingCapability === key + ? `Unknown command '${key}' - try 'help'` + : `${key} - supported command`; + } else if (command === 'bdinfo') { + response = this.options.memory ?? 'memstart = 0x80000000\nmemsize = 0x04000000'; + } else if (command === 'sf probe 0') { + response = `SF: Detected MX25L12805D with page size 256 Bytes, erase size 64 KiB, total ${this.options.flashMiB ?? 16} MiB`; + } else if (command.startsWith('crc32 ')) { + const [, address, length] = command.split(' '); + assert.equal(Number(address), RAM, 'checksum must cover the intended RAM buffer'); + const size = Number(length); + assert.ok(this.ram && this.ram.length >= size); + this.crcCalls++; + const checksum = this.options.badCrcAt === this.crcCalls ? '00000000' : crc32Hex(this.ram.subarray(0, size)); + response = `CRC32 for ${RAM.toString(16)} ... ${(RAM + size - 1).toString(16)} ==> ${checksum}`; + } else if (command.startsWith('sf erase ')) { + const [, , offset, length] = command.split(' '); + const start = Number(offset), size = Number(length); + assert.ok(SLOT_OFFSETS.includes(start), 'erase must start at an actual Nokia slot'); + assert.equal(size, 0x600000, 'erase includes the complete old JFFS2 overlay'); + assert.notEqual(start, SLOT_OFFSETS[this.originalProtectedSlot], 'never erase committed firmware'); + this.storage().fill(0xff, start, start + size); + response = `SF: ${size} bytes @ ${offset} Erased: OK`; + } else if (command.startsWith('sf write ')) { + const [, , address, offset, length] = command.split(' '); + assert.equal(Number(address), RAM); + const start = Number(offset), size = Number(length); + assert.equal(size, this.expectedSize, 'write file bytes, excluding YMODEM padding'); + this.storage().set(this.ram.subarray(0, size), start); + response = `SF: ${size} bytes @ ${offset} Written: OK`; + } else if (command.startsWith('sf read ')) { + const [, , address, offset, length] = command.split(' '); + assert.equal(Number(address), RAM); + const start = Number(offset), size = Number(length); + this.ram = this.storage().slice(start, start + size); + if (this.options.dirtyTail) this.ram[this.ram.length - 1] = 0x00; + response = `SF: ${size} bytes @ ${offset} Read: OK`; + } else if (command.startsWith('setenv ')) { + const [, key, remainder] = /^setenv ([A-Za-z0-9_]+)(?: (.*))?$/.exec(command) ?? []; + assert.ok(key, 'well-formed environment assignment'); + let value = remainder ?? null; + if (value?.startsWith("'")) { + assert.ok(value.endsWith("'")); + assert.ok(!value.slice(1, -1).includes("'")); + value = value.slice(1, -1); + } else if (value?.includes('$')) { + // Hush would expand unquoted variables now instead of later. + value = value.replace(/\$\{(\w+)\}|\$(\w+)/g, (_, a, b) => this.environment[a ?? b] ?? ''); + } + if (this.options.ignoreSetenv !== key) this.environment[key] = value; + response = ''; + } else if (command === 'saveenv') { + this.saves++; + this.persisted = { ...this.environment }; + response = 'Saving Environment to SPI Flash...\nErasing SPI flash...Writing to SPI flash...done'; + } else { + assert.fail(`Unexpected device command: ${command}`); + } + if (marker && this.options.omitMarkerFor !== command) response += `\n${marker}\n`; + return response; + } + + async write(text) { + this.checkAbort(); + assert.equal(text, 'loady 0x80800000\r'); + this.events.push('loady'); + this.receiverState = 'header'; + const address = this.options.readyAddress ?? '0x80800000'; + this.bytes.push(...encoder.encode(`## Ready for binary (ymodem) download to ${address} at 115200 bps...\r\n`), CRC_REQUEST); + } + + async readByte(deadline, signal) { + if (signal?.aborted) throw new DOMException('Cancelled', 'AbortError'); + this.checkAbort(); + if (Date.now() >= deadline || !this.bytes.length) throw Object.assign(new Error('No receiver byte'), { code: 'TIMEOUT' }); + return this.bytes.shift(); + } + + async writeBytes(packet) { + if (packet[0] === 0x18) { + this.events.push('ymodem-cancel'); + return; + } + this.checkAbort(); + if (packet.length === 1 && packet[0] === 0x04) { + assert.equal(this.receiverState, 'data'); + this.receiverState = 'final'; + // U-Boot's two-ACK EOT path followed by another CRC request. + this.bytes.push(ACK, ACK, CRC_REQUEST); + return; + } + const size = packet[0] === 0x01 ? 128 : packet[0] === 0x02 ? 1024 : 0; + assert.ok(size, 'SOH or STX packet'); + assert.equal(packet.length, size + 5); + assert.equal(packet[1] ^ packet[2], 0xff); + const payload = packet.subarray(3, 3 + size); + assert.equal(packet[3 + size] << 8 | packet[4 + size], crc16(payload), 'valid wire CRC16'); + if (this.receiverState === 'header') { + assert.equal(packet[1], 0); + const [filename, length] = decoder.decode(payload).split('\0'); + assert.equal(filename, 'nokia-firmware.image'); + this.expectedSize = Number(length); + this.receiverState = 'data'; + } else if (this.receiverState === 'data') { + assert.equal(packet[1], this.nextSequence & 0xff); + this.nextSequence++; + this.blocks.push(Uint8Array.from(payload)); + } else if (this.receiverState === 'final') { + assert.equal(packet[1], 0); + assert.ok(payload.every(value => value === 0), 'empty final batch header'); + this.ram = new Uint8Array(this.expectedSize); + let offset = 0; + for (const block of this.blocks) { + this.ram.set(block.subarray(0, Math.min(block.length, this.expectedSize - offset)), offset); + offset += Math.min(block.length, this.expectedSize - offset); + } + assert.equal(offset, this.expectedSize); + this.receiverState = 'complete'; + this.events.push('ymodem-complete'); + } else { + assert.fail(`Unexpected receiver state ${this.receiverState}`); + } + this.bytes.push(ACK); + } + + async waitPrompt() { + assert.equal(this.receiverState, 'complete'); + const size = this.expectedSize + (this.options.wrongTransferSize ? 1 : 0); + return `xyzModem - CRC mode, 1(SOH)/3(STX)/0(CAN) packets, 0 retries\n## Total Size = 0x${size.toString(16)} = ${size} Bytes\n`; + } + + destructiveCommands() { + return this.events.filter(value => /^(?:sf (?:erase|write)|setenv |saveenv\b|reset\b|bootm\b|run boot_image)/.test(value)); + } +} + +// Real Web Streams bridge for the shared text/binary console. In particular, +// the final YMODEM ACK and U-Boot's transfer report share one serial chunk. +class StreamFalconPort { + constructor(falcon) { + this.falcon = falcon; + this.closed = false; + } + + async open() { + this.readable = new ReadableStream({ start: controller => { this.controller = controller; } }); + this.writable = new WritableStream({ write: async bytes => { + const fake = this.falcon; + if ([0x01, 0x02, 0x04, 0x18].includes(bytes[0])) { + await fake.writeBytes(bytes); + const reply = fake.bytes.splice(0); + if (fake.receiverState === 'complete') reply.push(...encoder.encode((await fake.waitPrompt()) + 'FALCON => ')); + this.controller.enqueue(Uint8Array.from(reply)); + return; + } + const text = decoder.decode(bytes); + if (text === '\r') { + this.controller.enqueue(encoder.encode('FALCON => ')); + } else if (text.startsWith('echo __NOKIA_UART_')) { + this.controller.enqueue(encoder.encode(text.trim() + '\r\n' + text.slice(5).trim() + '\r\nFALCON => ')); + } else if (text.startsWith('loady ')) { + await fake.write(text); + this.controller.enqueue(Uint8Array.from([...encoder.encode(text + '\n'), ...fake.bytes.splice(0)])); + } else { + const command = text.replace(/\r$/, ''); + const response = await fake.command(command); + this.controller.enqueue(encoder.encode(command + '\r\n' + response + '\r\nFALCON => ')); + } + } }); + } + + async close() { + assert.equal(this.readable.locked, false); + assert.equal(this.writable.locked, false); + this.closed = true; + } +} + +function realConsole(port, signal) { + return new NokiaConsole(port, { + signal, baudRate: 115200, startupTimeoutMs: 1000, + commandTimeoutMs: 1000, ioTimeoutMs: 1000 + }); +} + +function run(serial, image = fixtureImage(), options = {}) { + return runNokiaFlashSession(serial, image, { + bootMode: 'stage', confirmFlash: async () => true, + commandTimeoutMs: 200, flashTimeoutMs: 300, transferTimeoutMs: 1000, + ...options + }); +} + +function assertProtected(serial, protectedSlot, image) { + const target = 1 - protectedSlot; + const offset = SLOT_OFFSETS[target]; + const memory = Buffer.from(serial.storage()); + assert.deepEqual(memory.subarray(0, offset), Buffer.alloc(offset, 0x5a)); + assert.deepEqual(memory.subarray(offset + 0x600000), Buffer.alloc(0x1000000 - offset - 0x600000, 0x5a)); + assert.deepEqual(memory.subarray(offset, offset + image.data.length), Buffer.from(image.data)); + assert.deepEqual(memory.subarray(offset + image.data.length, offset + 0x600000), Buffer.alloc(0x600000 - image.data.length, 0xff)); +} + +test('staging uses Nokia slot boundaries, verifies the whole erased tail, and preserves all other flash bytes', async t => { + for (const protectedSlot of [0, 1]) { + await t.test(`committed slot ${protectedSlot}`, async () => { + const image = fixtureImage(); + const serial = new FakeFalcon({ environment: { + commit: String(protectedSlot), next_active: String(protectedSlot), + c_img: String(1 - protectedSlot), image0_is_valid: '1', image1_is_valid: '1' + } }); + const before = { ...serial.environment }; + const result = await run(serial, image); + assert.equal(result.verified, true); + assert.equal(result.protectedSlot, protectedSlot); + assert.equal(result.targetSlot, 1 - protectedSlot); + assert.equal(result.offset, SLOT_OFFSETS[1 - protectedSlot]); + assertProtected(serial, protectedSlot, image); + assert.equal(serial.crcCalls, 2, 'RAM and full-slot readback checks'); + assert.equal(serial.saves, 0); + assert.deepEqual(serial.environment, before); + assert.ok(!serial.events.some(command => /^(setenv|saveenv|reset|bootm|run )/.test(command))); + const erase = serial.events.findIndex(command => command.startsWith('sf erase ')); + assert.ok(serial.events.indexOf('ymodem-complete') < erase); + assert.ok(serial.events.findIndex(command => command.startsWith('crc32 ')) < erase); + assert.equal(serial.receiverState, 'complete'); + }); + } +}); + +test('saved c_img never selects the protected slot; next_active=-1 uses the committed slot', () => { + const plan = planNokiaFlash(settings({ commit: '1', next_active: '-1', c_img: '0', image1_is_valid: '1' }), fixtureImage().metadata, 'stage'); + assert.equal(plan.protectedSlot, 1); + assert.equal(plan.targetSlot, 0); + assert.equal(plan.offset, 0x0c0000); +}); + +test('unknown boot geometry, scripts, and pending selectors cannot authorize erasing flash', async t => { + const invalid = [ + { kernel1_offs: '0x800000' }, + { kernel0_offs: '0x0' }, + { addmtdparts1: NOKIA_BOOT_PROFILE.addmtdparts1.replace('6144k', '7424k') }, + { bootcmd: 'run boot_image0' }, + { addip: 'sf erase 0 1000000' }, + { select_image: 'setenv c_img 0' }, + { update_system: 'run update_image1' }, + { boot_image1: 'sf erase 0 1000000' }, + { commit: '2' }, + { next_active: '1' }, + { image0_is_valid: '0' }, + { image1_is_valid: '2' }, + { boot_fail: 'unknown' }, + { boot_fail: null }, + { boot_fail: '8' }, + { asc0: '3' }, + { bootdelay: '0' }, + { bootdelay: '99999999999999999999' }, + { preboot: 'run custom_boot' } + ]; + for (const environment of invalid) { + await t.test(Object.keys(environment)[0] + '=' + Object.values(environment)[0], async () => { + const serial = new FakeFalcon({ environment }); + await assert.rejects(run(serial)); + assert.deepEqual(serial.destructiveCommands(), []); + assert.ok(!serial.events.includes('loady')); + }); + } +}); + +test('version, RAM, required command, and flash-capacity checks fail before transfer', async t => { + for (const options of [ + { version: 'U-Boot 2011.12-lantiq-gpon-1.2.24' }, + { version: 'U-Boot 2015.04-lantiq-gpon-1.3.6.1 (Mar 28 2017 - 11:55:00)' }, + { memory: 'memstart = 0x80000000\nmemsize = 0x02000000' }, + { memory: 'memstart = 0xa0000000\nmemsize = 0x04000000' }, + { missingCapability: 'loady' }, + { missingCapability: 'crc32' }, + { missingCapability: 'sf' }, + { flashMiB: 8 } + ]) { + await t.test(JSON.stringify(options), async () => { + const serial = new FakeFalcon(options); + await assert.rejects(run(serial)); + assert.deepEqual(serial.destructiveCommands(), []); + assert.ok(!serial.events.includes('loady')); + }); + } +}); + +test('an untrusted filesize or kernel larger than the read window is rejected', () => { + const image = fixtureImage().metadata; + for (const bad of [ + { ...image, size: 0x600001 }, + { ...image, size: 0 }, + { ...image, slotSize: 0x740000 }, + { ...image, kernelSize: 0x180000 } + ]) assert.throws(() => planNokiaFlash(settings(), bad, 'stage'), { code: 'IMAGE_SIZE' }); +}); + +test('backup and explicit confirmation precede any transfer or flash mutation', async () => { + const serial = new FakeFalcon(); + let backup; + await assert.rejects(run(serial, fixtureImage(), { + onBackup(value) { + backup = value; + assert.deepEqual(serial.destructiveCommands(), []); + assert.ok(!serial.events.includes('loady')); + }, + confirmFlash(plan) { + assert.equal(backup.settings.commit, '0'); + assert.equal(backup.plan.targetSlot, plan.targetSlot); + assert.equal(plan.targetSlot, 1); + return false; + } + }), { name: 'AbortError' }); + assert.deepEqual(serial.destructiveCommands(), []); + assert.ok(!serial.events.includes('loady')); +}); + +test('a device-setting change while the user reviews the plan stops before transfer', async () => { + const serial = new FakeFalcon(); + await assert.rejects(run(serial, fixtureImage(), { + confirmFlash() { + serial.environment.next_active = '1'; + return true; + } + }), { code: 'SETTINGS_CHANGED' }); + assert.deepEqual(serial.destructiveCommands(), []); + assert.ok(!serial.events.includes('loady')); +}); + +test('a boot-state change during YMODEM stops after RAM verification and before erase', async () => { + const image = fixtureImage(); + const serial = new FakeFalcon(); + await assert.rejects(run(serial, image, { + onProgress(sent) { + if (sent === image.data.length) serial.environment.next_active = '1'; + } + }), { code: 'SETTINGS_CHANGED' }); + assert.equal(serial.receiverState, 'complete'); + assert.equal(serial.crcCalls, 1); + assert.deepEqual(serial.destructiveCommands(), []); +}); + +test('wrong receiver address, received length, or RAM checksum never reaches erase', async t => { + for (const options of [ + { readyAddress: '0x80002000' }, + { wrongTransferSize: true }, + { badCrcAt: 1 } + ]) { + await t.test(JSON.stringify(options), async () => { + const serial = new FakeFalcon(options); + await assert.rejects(run(serial)); + assert.deepEqual(serial.destructiveCommands(), []); + }); + } +}); + +test('flash readback covers the old overlay tail and forbids activation on any mismatch', async t => { + for (const options of [{ badCrcAt: 2 }, { dirtyTail: true }]) { + await t.test(JSON.stringify(options), async () => { + const serial = new FakeFalcon(options); + await assert.rejects(run(serial, fixtureImage(), { bootMode: 'trial' }), { code: 'FLASH_UNCERTAIN' }); + assert.equal(serial.crcCalls, 2); + assert.equal(serial.saves, 0); + assert.ok(!serial.events.some(command => command.startsWith('setenv '))); + assert.equal(serial.persisted.commit, '0'); + assert.equal(serial.persisted.next_active, '0'); + }); + } +}); + +test('a prompt without the fresh success marker cannot establish a completed flash command', async () => { + const serial = new FakeFalcon({ omitMarkerFor: 'sf erase 0x6c0000 0x600000' }); + await assert.rejects(run(serial), { code: 'FLASH_UNCERTAIN' }); + assert.ok(serial.events.some(command => command.startsWith('sf erase '))); + assert.ok(!serial.events.some(command => command.startsWith('sf write '))); + assert.equal(serial.saves, 0); +}); + +test('write errors cannot be hidden by a shell success marker', async () => { + const serial = new FakeFalcon({ + onCommand(command, self, raw) { + if (command.startsWith('sf write ')) { + const marker = raw.match(/echo (\S+)$/)[1]; + return `SF: write ERROR\nError: program operation failed\n${marker}\n`; + } + } + }); + await assert.rejects(run(serial), { code: 'FLASH_UNCERTAIN' }); + assert.ok(!serial.events.some(command => command.startsWith('sf read '))); + assert.equal(serial.saves, 0); +}); + +test('cancelling a pending review cannot later resume the operation', { timeout: 1000 }, async () => { + const controller = new AbortController(); + const serial = new FakeFalcon({ signal: controller.signal }); + let resolveReview; + let reviewing; + const ready = new Promise(resolve => { reviewing = resolve; }); + const operation = run(serial, fixtureImage(), { + signal: controller.signal, + confirmFlash() { + reviewing(); + return new Promise(resolve => { resolveReview = resolve; }); + } + }); + await ready; + controller.abort(); + await assert.rejects(operation, { name: 'AbortError' }); + const count = serial.commands.length; + resolveReview(true); + await new Promise(resolve => setTimeout(resolve, 10)); + assert.equal(serial.commands.length, count); + assert.deepEqual(serial.destructiveCommands(), []); +}); + +test('cancellation immediately before erase keeps the flash untouched', async () => { + const controller = new AbortController(); + const serial = new FakeFalcon({ signal: controller.signal }); + await assert.rejects(run(serial, fixtureImage(), { + signal: controller.signal, + onPhase(phase) { if (phase === 'erase') controller.abort(); } + }), { name: 'AbortError' }); + assert.deepEqual(serial.destructiveCommands(), []); +}); + +test('cancellation after erase reports partial flash and never activates it', async () => { + const controller = new AbortController(); + const serial = new FakeFalcon({ signal: controller.signal }); + await assert.rejects(run(serial, fixtureImage(), { + signal: controller.signal, bootMode: 'trial', + onPhase(phase) { if (phase === 'write') controller.abort(); } + }), { code: 'FLASH_UNCERTAIN' }); + assert.ok(serial.events.some(command => command.startsWith('sf erase '))); + assert.ok(!serial.events.some(command => command.startsWith('sf write '))); + assert.equal(serial.saves, 0); + assert.equal(serial.persisted.next_active, '0'); +}); + +test('changed inspected bytes are rejected before device commands', async () => { + const image = fixtureImage(); + image.data[0] ^= 1; + const serial = new FakeFalcon(); + await assert.rejects(run(serial, image), { code: 'IMAGE_CHANGED' }); + assert.deepEqual(serial.commands, []); +}); + +test('the public entry point rejects an unrecognized image before opening a port', async () => { + let opens = 0; + const port = { open() { opens++; assert.fail('invalid input must not open UART'); } }; + await assert.rejects(flashNokiaFirmware(port, Uint8Array.of(1, 2, 3), { confirmFlash: () => true })); + assert.equal(opens, 0); +}); + +test('trial migration is saved only after readback and preserves the committed image', async () => { + const image = fixtureImage(); + const serial = new FakeFalcon(); + const oldSelector = serial.environment.select_image; + let backup; + const result = await run(serial, image, { bootMode: 'trial', onBackup: value => { backup = value; } }); + assert.equal(result.bootMode, 'trial'); + assert.equal(serial.persisted.commit, '0', 'legacy selector remains available for rollback'); + assert.equal(serial.persisted.committed_image, '0', 'old firmware remains the default'); + assert.equal(serial.persisted.next_active, '1', 'new firmware is requested once'); + assert.equal(serial.persisted.image0_is_valid, '1'); + assert.equal(serial.persisted.image1_is_valid, '1'); + assert.equal(serial.persisted.boot_fail, '0'); + for (const [key, value] of Object.entries(NOKIA_UPGRADE_SETTINGS)) assert.equal(serial.persisted[key], value); + assert.match(serial.persisted.select_image, /setenv boot_fail 0;exit 0$/); + assert.ok(serial.persisted.select_image.includes('${magic_addr}'), 'boot-time variable expansions remain literal'); + assert.equal(backup.settings.select_image, oldSelector); + assert.equal(backup.settings.committed_image, null); + assert.equal(backup.plan.migrateBootScripts, true); + assert.equal(serial.saves, 1); + const firstMutation = serial.events.findIndex(command => command.startsWith('setenv ')); + const checksums = serial.events.flatMap((command, index) => command.startsWith('crc32 ') ? [index] : []); + assert.ok(firstMutation > checksums[1], 'no environment mutation before full flash proof'); + const assignedSelector = serial.commands.find(command => command.startsWith('setenv select_image ')); + assert.ok(assignedSelector.startsWith("setenv select_image '")); + assert.match(assignedSelector, /' && echo __NOKIA_FLASH_[a-f0-9]+__$/); + assert.ok(encoder.encode(assignedSelector + '\r').length < 1023, 'complete long script and nonce fit inspected console'); + assert.ok(!serial.events.some(command => /^(?:bootm|reset|run )/.test(command)), 'no automatic kernel start or reset'); + assertProtected(serial, 0, image); +}); + +test('explicit default-image activation migrates the policy without erasing the old image', async () => { + const image = fixtureImage(); + const serial = new FakeFalcon(); + const result = await run(serial, image, { bootMode: 'commit' }); + assert.equal(result.bootMode, 'commit'); + assert.equal(serial.persisted.commit, '0', 'old legacy value is not repurposed'); + assert.equal(serial.persisted.committed_image, '1'); + assert.equal(serial.persisted.next_active, '1'); + assert.equal(serial.persisted.image0_is_valid, '1'); + assert.equal(serial.persisted.boot_fail, '0'); + assert.equal(serial.persisted.select_image, NOKIA_UPGRADE_SETTINGS.select_image); + assert.equal(serial.saves, 1); + assertProtected(serial, 0, image); +}); + +test('a migrated profile protects committed_image rather than an obsolete legacy commit', async () => { + const serial = new FakeFalcon({ environment: { + ...NOKIA_UPGRADE_SETTINGS, + commit: '0', committed_image: '1', next_active: '1', c_img: '0', + image0_is_valid: '0', image1_is_valid: '1' + } }); + let reviewed; + const result = await run(serial, fixtureImage(), { + bootMode: 'trial', confirmFlash(plan) { reviewed = plan; return true; } + }); + assert.equal(reviewed.bootProfile, '19.07'); + assert.equal(reviewed.migrateBootScripts, false); + assert.equal(result.protectedSlot, 1); + assert.equal(result.targetSlot, 0); + assert.equal(result.offset, 0x0c0000); + assert.equal(serial.persisted.commit, '0'); + assert.equal(serial.persisted.committed_image, '1'); + assert.equal(serial.persisted.next_active, '0'); + assert.ok(!serial.events.some(command => /^setenv (?:select_image|update_system|boot_image) /.test(command)), 'already migrated scripts are not rewritten'); +}); + +test('partial migration or a pending migrated trial is not guessed', async t => { + for (const environment of [ + { select_image: NOKIA_UPGRADE_SETTINGS.select_image, committed_image: '0' }, + { ...NOKIA_UPGRADE_SETTINGS, committed_image: null }, + { ...NOKIA_UPGRADE_SETTINGS, committed_image: '0', next_active: '1' } + ]) { + await t.test(JSON.stringify(environment).slice(0, 90), async () => { + const serial = new FakeFalcon({ environment }); + await assert.rejects(run(serial)); + assert.deepEqual(serial.destructiveCommands(), []); + }); + } +}); + +test('a migration readback mismatch prevents saveenv and retains the original persistent settings', async () => { + const serial = new FakeFalcon({ ignoreSetenv: 'select_image' }); + const persisted = { ...serial.persisted }; + await assert.rejects(run(serial, fixtureImage(), { bootMode: 'commit' }), { code: 'SAVE_UNCERTAIN' }); + assert.equal(serial.crcCalls, 2); + assert.ok(serial.events.some(command => command.startsWith('setenv select_image '))); + assert.equal(serial.saves, 0); + assert.deepEqual(serial.persisted, persisted); + assert.ok(!serial.events.some(command => /^(?:bootm|reset|run )/.test(command))); +}); + +test('a missing saveenv acknowledgement is an uncertain activation, never success', async () => { + const serial = new FakeFalcon({ omitMarkerFor: 'saveenv' }); + await assert.rejects(run(serial, fixtureImage(), { bootMode: 'trial' }), error => { + assert.equal(error.code, 'SAVE_UNCERTAIN'); + assert.match(error.message, /may not be saved/); + return true; + }); + assert.equal(serial.saves, 1, 'no blind retry of a possibly completed flash save'); + assert.equal(serial.crcCalls, 2); + assert.ok(!serial.events.some(command => /^(?:bootm|reset|run )/.test(command))); +}); + +test('disconnecting during saveenv cannot be reported as an ordinary cancelled operation', async () => { + const serial = new FakeFalcon({ + onCommand(command, self) { + if (command === 'saveenv') { + self.saves++; + throw Object.assign(new Error('USB disconnected'), { code: 'DISCONNECTED' }); + } + } + }); + await assert.rejects(run(serial, fixtureImage(), { bootMode: 'commit' }), { code: 'SAVE_UNCERTAIN' }); + assert.equal(serial.saves, 1); + assert.equal(serial.persisted.next_active, '0'); +}); + +test('cancelling during an environment migration reports partial in-RAM edits without saving them', async () => { + const controller = new AbortController(); + const serial = new FakeFalcon({ + signal: controller.signal, + onCommand(command) { + if (command.startsWith('setenv select_image ')) controller.abort(); + } + }); + await assert.rejects(run(serial, fixtureImage(), { signal: controller.signal, bootMode: 'commit' }), { code: 'SAVE_UNCERTAIN' }); + assert.equal(serial.saves, 0); + assert.equal(serial.persisted.select_image, NOKIA_BOOT_PROFILE.select_image); + assert.ok(serial.events.some(command => command.startsWith('setenv select_image '))); + assert.ok(!serial.events.some(command => /^(?:bootm|reset|run )/.test(command))); +}); + +test('a settings change after flash verification stops activation', async () => { + const serial = new FakeFalcon(); + await assert.rejects(run(serial, fixtureImage(), { + bootMode: 'trial', + onPhase(phase) { if (phase === 'activate') serial.environment.bootdelay = '3'; } + }), { code: 'FLASH_UNCERTAIN' }); + assert.equal(serial.crcCalls, 2); + assert.ok(!serial.events.some(command => command.startsWith('setenv '))); + assert.equal(serial.saves, 0); +}); + +test('CRC warnings and multiple environment values are not accepted as a verified profile', async t => { + for (const response of [ + 'Warning: bad CRC, using default environment\ncommit=0', + 'commit=0\ncommit=1', + '## Error: "commit" not defined\ncommit=0' + ]) { + await t.test(response, async () => { + const serial = new FakeFalcon({ onCommand: command => command === 'printenv commit' ? response : undefined }); + await assert.rejects(run(serial), { code: 'ENVIRONMENT' }); + assert.deepEqual(serial.destructiveCommands(), []); + }); + } +}); + +test('a stale or duplicated CRC line is not accepted as RAM verification', async () => { + const serial = new FakeFalcon({ + onCommand(command, self, raw) { + if (command.startsWith('crc32 ')) { + const marker = raw.match(/echo (\S+)$/)[1]; + const line = `CRC32 for ${RAM.toString(16)} ... ${(RAM + self.expectedSize - 1).toString(16)} ==> ${crc32Hex(self.ram)}`; + return `${line}\n${line}\n${marker}\n`; + } + } + }); + await assert.rejects(run(serial), { code: 'CRC_MISMATCH' }); + assert.deepEqual(serial.destructiveCommands(), []); +}); + +test('real console accepts an explicit version reply and preserves coalesced YMODEM ACK/prompt bytes', async () => { + const image = fixtureImage(); + const device = new FakeFalcon(); + const port = new StreamFalconPort(device); + const serial = realConsole(port); + try { + await serial.open(); + await serial.acquire(); + const result = await run(serial, image, { bootMode: 'commit', commandTimeoutMs: 1000, flashTimeoutMs: 1000 }); + assert.equal(result.verified, true); + assert.equal(device.receiverState, 'complete'); + assert.equal(device.saves, 1); + assert.equal(device.persisted.committed_image, '1'); + assert.equal(device.persisted.select_image, NOKIA_UPGRADE_SETTINGS.select_image); + assertProtected(device, 0, image); + } finally { + await serial.close(); + } + assert.equal(port.closed, true); +}); + +test('the version-command exemption still rejects a real reboot', async () => { + const device = new FakeFalcon({ + onCommand: command => command === 'version' + ? 'ROM: V1.1.4\nChip: FALCON-S (A22)\nU-Boot 2015.04-lantiq-gpon-1.3.6.1 (Feb 07 2018 - 17:12:06)' + : undefined + }); + const port = new StreamFalconPort(device); + const serial = realConsole(port); + try { + await serial.open(); + await serial.acquire(); + await assert.rejects(run(serial), { code: 'DISCONNECTED' }); + assert.deepEqual(device.destructiveCommands(), []); + } finally { + await serial.close(); + } +}); + +test('a boot banner during an unrelated command still invalidates the verified console', async () => { + const device = new FakeFalcon({ + onCommand: command => command === 'printenv commit' + ? 'U-Boot 2015.04-lantiq-gpon-1.3.6.1 (Feb 07 2018 - 17:12:06)' + : undefined + }); + const port = new StreamFalconPort(device); + const serial = realConsole(port); + try { + await serial.open(); + await serial.acquire(); + await assert.rejects(run(serial), { code: 'DISCONNECTED' }); + assert.deepEqual(device.destructiveCommands(), []); + } finally { + await serial.close(); + } +}); + +test('real byte transport sends CAN cleanup even after the operation signal is aborted', async () => { + const controller = new AbortController(); + const packets = []; + let input; + const port = { + async open() { + this.readable = new ReadableStream({ start: stream => { input = stream; input.enqueue(Uint8Array.of(CRC_REQUEST)); } }); + this.writable = new WritableStream({ write: async bytes => { + packets.push(Uint8Array.from(bytes)); + if (bytes[0] !== 0x18) input.enqueue(Uint8Array.of(ACK)); + } }); + }, + async close() {} + }; + const serial = realConsole(port, controller.signal); + try { + await serial.open(); + await assert.rejects(sendYmodem(serial, Uint8Array.of(1, 2, 3), { + signal: controller.signal, + onProgress: () => controller.abort(), + startupTimeoutMs: 200, responseTimeoutMs: 200, transferTimeoutMs: 1000 + }), { name: 'AbortError' }); + assert.deepEqual([...packets.at(-1)], [0x18, 0x18, 0x18, 0x18, 0x08, 0x08, 0x08, 0x08]); + assert.equal(packets.filter(packet => packet[0] === 0x18).length, 1); + } finally { + await serial.close(); + } +}); diff --git a/tests/nokiaImage.test.js b/tests/nokiaImage.test.js new file mode 100644 index 00000000..53f5a315 --- /dev/null +++ b/tests/nokiaImage.test.js @@ -0,0 +1,153 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { crc32Hex, inspectNokiaImage, NOKIA_SLOT_SIZE } from '../.vitepress/theme/lib/nokiaImage.js'; + +// Python-generated LZMA test payload and uImage checksums, followed by a small +// synthetic SquashFS superblock. This is not bootable firmware and contains no +// bytes from the submitted proprietary images. +const FIXTURE = 'JwUZVhRAu5liWsD8AAAAOoAAIACAACAA2OymmgUFAgNNSVBTIE9wZW5XcnQgTGludXgtMy4xMC4xMDgAAAAAAF0AAIAA//////////8AKZ5Jx3eqw+J02qzRRqE0NwJK2/TTns5O2tJmEy/+93HUrdDxFhGeP/4pagBoc3FzAwAAALuofmoAAAQAAAAAAAQAEgDAAAEABAAAAAAAAAAAAAAAAAEAAAAAAAD4AAAAAAAAAP//////////ZAAAAAAAAACMAAAAAAAAAP//////////4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; +const REVIEWED_SHA256 = '5c0d6853645d72748cf844f9e64fc57c38924cc7938ef14a40a827015bbc1248'; +const ROOTFS_OFFSET = 122; + +function fixture() { + return Uint8Array.from(Buffer.from(FIXTURE, 'base64')); +} + +function repairHeader(bytes) { + bytes.fill(0, 4, 8); + new DataView(bytes.buffer, bytes.byteOffset).setUint32(4, Number.parseInt(crc32Hex(bytes.subarray(0, 64)), 16), false); +} + +test('CRC32 agrees with independent standard and fixture vectors, including byte views', () => { + assert.equal(crc32Hex(new TextEncoder().encode('123456789')), 'cbf43926'); + assert.equal(crc32Hex(new Uint8Array()), '00000000'); + assert.equal(crc32Hex(fixture()), '45ec4781'); + assert.equal(crc32Hex(new TextEncoder().encode('x123456789y').subarray(1, 10)), 'cbf43926'); + assert.throws(() => crc32Hex(new ArrayBuffer(1)), TypeError); +}); + +test('rejects non-byte input, empty/truncated images, oversized images and full dumps', async () => { + for (const input of [null, new ArrayBuffer(200), [], new Uint8Array(), new Uint8Array(63)]) { + await assert.rejects(inspectNokiaImage(input), { code: 'INVALID_IMAGE' }); + } + for (const length of [NOKIA_SLOT_SIZE + 1, 0x1000000]) { + await assert.rejects(inspectNokiaImage(new Uint8Array(length)), { code: 'IMAGE_TOO_LARGE' }); + } +}); + +test('generic MIPS uImage/SquashFS structure cannot authorize a model', async () => { + await assert.rejects(inspectNokiaImage(fixture()), { code: 'UNSUPPORTED_IMAGE' }); + const padded = new Uint8Array(NOKIA_SLOT_SIZE).fill(0xff); + padded.set(fixture()); + await assert.rejects(inspectNokiaImage(padded), { code: 'UNSUPPORTED_IMAGE' }); +}); + +test('rejects bad magic and independent header/payload corruption', async () => { + const magic = fixture(); + magic[0] ^= 1; + await assert.rejects(inspectNokiaImage(magic), { code: 'INVALID_UIMAGE' }); + const header = fixture(); + header[8] ^= 1; + await assert.rejects(inspectNokiaImage(header), { code: 'BAD_HEADER_CRC' }); + const kernel = fixture(); + kernel[70] ^= 1; + await assert.rejects(inspectNokiaImage(kernel), { code: 'BAD_KERNEL_CRC' }); +}); + +test('rejects wrong kernel type/architecture/compression or load address with valid header CRC', async () => { + for (const offset of [16, 20, 28, 29, 30, 31]) { + const bytes = fixture(); + bytes[offset] ^= 1; + repairHeader(bytes); + await assert.rejects(inspectNokiaImage(bytes), { code: 'UNSUPPORTED_UIMAGE' }); + } +}); + +test('rejects zero, truncated and overflowing kernel lengths before reading out of bounds', async () => { + for (const size of [0, 12, 1000, 0xffffffff]) { + const bytes = fixture(); + new DataView(bytes.buffer).setUint32(12, size, false); + repairHeader(bytes); + await assert.rejects(inspectNokiaImage(bytes), { code: 'INVALID_KERNEL_SIZE' }); + } +}); + +test('requires SquashFS 4.0/XZ exactly after the kernel', async () => { + for (const offset of [0, 20, 28, 30]) { + const bytes = fixture(); + bytes[ROOTFS_OFFSET + offset] ^= 1; + await assert.rejects(inspectNokiaImage(bytes), { code: 'INVALID_SQUASHFS' }); + } +}); + +test('rejects rootfs lengths and metadata references outside the image', async () => { + const cases = [ + view => view.setBigUint64(40, 0xffffffffffffffffn, true), + view => view.setBigUint64(40, 257n, true), + view => view.setBigUint64(40, 95n, true), + view => view.setBigUint64(48, 256n, true), + view => view.setBigUint64(48, 252n, true), + view => view.setBigUint64(56, 256n, true), + view => view.setBigUint64(64, 95n, true), + view => view.setBigUint64(72, 99n, true), + view => view.setBigUint64(80, 256n, true), + view => view.setBigUint64(88, 256n, true), + view => view.setBigUint64(32, 8192n, true), + view => view.setBigUint64(32, 40n << 16n, true), + view => view.setUint32(4, 0, true), + view => view.setUint16(26, 0, true), + view => view.setUint16(22, 30, true), + view => view.setUint32(12, 131072, true), + view => view.setUint32(16, 1, true) + ]; + for (const change of cases) { + const bytes = fixture(); + change(new DataView(bytes.buffer, ROOTFS_OFFSET)); + await assert.rejects(inspectNokiaImage(bytes), { code: 'INVALID_SQUASHFS' }); + } +}); + +test('a recognized digest still requires its reviewed size', async t => { + // Only the crypto result is stubbed: there is no production option to + // disable the allowlist or supply an alternative trusted hash. + t.mock.method(globalThis.crypto.subtle, 'digest', async () => Buffer.from(REVIEWED_SHA256, 'hex')); + await assert.rejects(inspectNokiaImage(fixture()), { code: 'UNSUPPORTED_IMAGE' }); +}); + +test('metadata is frozen and inspection snapshots mutable buffers across SHA-256 await', async t => { + const input = Buffer.alloc(0x4400eb, 0xff); + input.set(fixture()); + const expectedCrc = crc32Hex(input); + t.mock.method(globalThis.crypto.subtle, 'digest', async (algorithm, bytes) => { + assert.equal(algorithm, 'SHA-256'); + assert.notEqual(bytes.buffer, input.buffer); + input.fill(0); + assert.equal(bytes[0], 0x27); + return Buffer.from(REVIEWED_SHA256, 'hex'); + }); + const result = await inspectNokiaImage(input); + assert.deepEqual(result, { + profile: 'g010sa-19.07-20260814', + name: 'Nokia G-010S-A OpenWrt 19.07 (2026-08-14)', + size: 0x4400eb, + sha256: REVIEWED_SHA256, + crc32: expectedCrc, + kernelSize: 58, + rootfsOffset: ROOTFS_OFFSET, + rootfsSize: 256, + slotSize: 0x600000 + }); + assert.ok(Object.isFrozen(result)); + assert.throws(() => { result.crc32 = '00000000'; }, TypeError); +}); + +test('fails closed if SHA-256 verification is unavailable or fails', async t => { + await t.test('unavailable', async t => { + t.mock.getter(globalThis, 'crypto', () => undefined); + await assert.rejects(inspectNokiaImage(fixture()), { code: 'CRYPTO_UNAVAILABLE' }); + }); + await t.test('digest failure', async t => { + t.mock.method(globalThis.crypto.subtle, 'digest', async () => { throw new Error('crypto failed'); }); + await assert.rejects(inspectNokiaImage(fixture()), /crypto failed/); + }); +}); diff --git a/tests/nokiaSerial.test.js b/tests/nokiaSerial.test.js index 39449681..605cc193 100644 --- a/tests/nokiaSerial.test.js +++ b/tests/nokiaSerial.test.js @@ -181,6 +181,13 @@ test('a U-Boot banner alone does not authorize commands', { timeout: 1000 }, asy assert.deepEqual(port.commands(), []); }); +test('a bad saved environment warning at boot is rejected before its prompt is discarded', async () => { + const port = new FakePort({ initial: ['Warning: bad CRC, using default environment\r\n'] }); + await assert.rejects(run(port), { code: 'BAD_ENVIRONMENT' }); + assert.deepEqual(port.mutations(), []); + assert.equal(port.closeCount, 1); +}); + test('continuous irrelevant output does not extend the overall timeout', { timeout: 1000 }, async () => { const port = new FakePort({ promptOnCR: false, noise: true }); await assert.rejects(run(port, { startupTimeoutMs: 70 }), { code: 'TIMEOUT' }); @@ -295,7 +302,7 @@ test('CRC/environment errors are not treated as undefined variables', async () = return true; } }); - await assert.rejects(run(port), { code: 'COMMAND_FAILED' }); + await assert.rejects(run(port), { code: 'BAD_ENVIRONMENT' }); assert.deepEqual(port.mutations(), []); }); diff --git a/tests/ymodem.test.js b/tests/ymodem.test.js new file mode 100644 index 00000000..1ae27166 --- /dev/null +++ b/tests/ymodem.test.js @@ -0,0 +1,362 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { sendYmodem } from '../.vitepress/theme/lib/ymodem.js'; + +const SOH = 0x01, STX = 0x02, EOT = 0x04, ACK = 0x06, NAK = 0x15, CAN = 0x18, C = 0x43; +const FAST = { startupTimeoutMs: 80, responseTimeoutMs: 35, writeTimeoutMs: 80, transferTimeoutMs: 2000 }; +const decoder = new TextDecoder(); +const encoder = new TextEncoder(); + +// Independent bytewise CRC-CCITT reference, including a known check vector. +function referenceCrc(bytes) { + let crc = 0; + for (const byte of bytes) { + let value = ((crc >>> 8) ^ byte) & 0xff; + value ^= value >>> 4; + crc = ((crc << 8) ^ (value << 12) ^ (value << 5) ^ value) & 0xffff; + } + return crc; +} +assert.equal(referenceCrc(encoder.encode('123456789')), 0x31c3); + +function timeout() { + return Object.assign(new Error('Serial read deadline reached'), { code: 'TIMEOUT' }); +} + +// This receiver models the relevant U-Boot/standard YMODEM wire behaviour, not +// the sender's functions. Its byte queue deliberately retains coalesced output. +class Receiver { + constructor({ headerC = false, firstEotNak = false, doubleAck = true, initial = [C], + onPacket, dropDataAck = -1, split = false, trailer = '\r\n## Total Size = ready\r\nFALCON => ' } = {}) { + Object.assign(this, { headerC, firstEotNak, doubleAck, onPacket, dropDataAck, split, trailer }); + this.chunks = []; + this.writes = []; + this.phase = 'header'; + this.expected = 1; + this.accepted = []; + this.attempts = new Map(); + this.eots = 0; + this.cancels = 0; + this.dropped = false; + this.enqueue(Uint8Array.from(initial)); + } + + enqueue(bytes) { + if (bytes.length) { + if (this.split) for (const byte of bytes) this.chunks.push(Uint8Array.of(byte)); + else this.chunks.push(bytes.slice()); + } + if (this.pending && this.chunks.length) this.pending.finish(null, this.take()); + } + + take() { + const byte = this.chunks[0][0]; + this.chunks[0] = this.chunks[0].subarray(1); + if (!this.chunks[0].length) this.chunks.shift(); + return byte; + } + + remaining() { + return Uint8Array.from(this.chunks.flatMap(chunk => [...chunk])); + } + + async readByte(deadline, signal) { + if (signal?.aborted) throw new DOMException('Cancelled', 'AbortError'); + if (Date.now() >= deadline) throw timeout(); + if (this.chunks.length) return this.take(); + assert.equal(this.pending, undefined, 'there must only be one pending read'); + return new Promise((resolve, reject) => { + const finish = (error, byte) => { + clearTimeout(timer); + signal?.removeEventListener('abort', abort); + this.pending = undefined; + if (error) reject(error); + else resolve(byte); + }; + const abort = () => finish(new DOMException('Cancelled', 'AbortError')); + const timer = setTimeout(() => finish(timeout()), Math.max(0, deadline - Date.now())); + this.pending = { finish }; + signal?.addEventListener('abort', abort, { once: true }); + }); + } + + async writeBytes(bytes, deadline, signal) { + if (signal?.aborted) throw new DOMException('Cancelled', 'AbortError'); + if (Date.now() >= deadline) throw timeout(); + this.writes.push(bytes.slice()); + if (bytes[0] === CAN) { + this.cancels++; + return; + } + if (bytes[0] === EOT) { + assert.equal(bytes.length, 1); + this.eots++; + if (this.firstEotNak && this.eots === 1) { + this.enqueue(Uint8Array.of(NAK)); + } else { + this.phase = 'final'; + this.enqueue(Uint8Array.from(this.doubleAck ? [ACK, ACK, C] : [ACK, C])); + } + return; + } + const payloadSize = bytes[0] === SOH ? 128 : 1024; + assert.ok(bytes[0] === SOH || bytes[0] === STX, 'valid YMODEM packet type'); + assert.equal(bytes.length, payloadSize + 5); + assert.equal(bytes[1] ^ bytes[2], 0xff); + const payload = bytes.subarray(3, bytes.length - 2); + assert.equal((bytes.at(-2) << 8) | bytes.at(-1), referenceCrc(payload), 'valid wire CRC'); + const key = `${this.phase}/${this.accepted.length}/${bytes[1]}`; + const attempt = (this.attempts.get(key) ?? 0) + 1; + this.attempts.set(key, attempt); + if (await this.onPacket?.({ phase: this.phase, sequence: bytes[1], bytes, payload, attempt }, this)) return; + + if (this.phase === 'header') { + assert.equal(bytes[0], SOH); + assert.equal(bytes[1], 0); + const fields = decoder.decode(payload).split('\0'); + this.filename = fields[0]; + this.length = Number(fields[1]); + this.phase = 'data'; + this.enqueue(Uint8Array.from(this.headerC ? [ACK, C] : [ACK])); + } else if (this.phase === 'data') { + if (this.lastPacket && bytes[1] === this.lastPacket[1]) { + assert.deepEqual(bytes, this.lastPacket, 'a retry sends the identical packet'); + this.enqueue(Uint8Array.of(ACK)); + return; + } + assert.equal(bytes[1], this.expected, 'sequential modulo-256 data packets'); + this.expected = (this.expected + 1) & 0xff; + this.lastPacket = bytes.slice(); + this.accepted.push(payload.slice()); + if (!this.dropped && this.accepted.length === this.dropDataAck) this.dropped = true; + else this.enqueue(Uint8Array.of(ACK)); + } else { + assert.equal(bytes[0], SOH); + assert.equal(bytes[1], 0); + assert.ok(payload.every(byte => byte === 0), 'end-of-batch header is empty'); + this.enqueue(Uint8Array.from([ACK, ...encoder.encode(this.trailer)])); + this.phase = 'complete'; + } + } + + file() { + const bytes = new Uint8Array(this.accepted.length * 1024); + this.accepted.forEach((block, index) => bytes.set(block, index * 1024)); + return bytes.subarray(0, this.length); + } +} + +const sample = length => Uint8Array.from({ length }, (_, index) => (index * 37 + 19) & 0xff); +const run = (io, bytes, options = {}) => sendYmodem(io, bytes, { ...FAST, ...options }); + +test('U-Boot ACK-only header and double-ACK EOT preserve the exact file and console tail', async () => { + const bytes = sample(2049); + bytes[2048] = 0x1a; // A real file-ending Ctrl-Z must survive YMODEM padding. + const receiver = new Receiver(); + const progress = []; + const result = await run(receiver, bytes, { onProgress: value => progress.push(value) }); + assert.deepEqual(result, { bytesSent: 2049, retries: 0 }); + assert.equal(receiver.filename, 'firmware.image'); + assert.equal(receiver.length, bytes.length); + assert.deepEqual(receiver.file(), bytes); + assert.deepEqual(progress, [1024, 2048, 2049]); + assert.equal(receiver.phase, 'complete'); + assert.equal(receiver.eots, 1); + assert.equal(receiver.cancels, 0); + assert.equal(decoder.decode(receiver.remaining()), receiver.trailer); +}); + +test('standard header ACK+C and first-EOT NAK work with byte-split replies', async () => { + const bytes = sample(1100); + const receiver = new Receiver({ headerC: true, firstEotNak: true, doubleAck: false, split: true }); + const result = await run(receiver, bytes, { filename: 'nokia.image' }); + assert.deepEqual(receiver.file(), bytes); + assert.equal(receiver.filename, 'nokia.image'); + assert.equal(receiver.eots, 2); + assert.equal(result.retries, 1); + assert.equal(decoder.decode(receiver.remaining()), receiver.trailer); +}); + +test('data block numbering wraps through zero without changing the payload', async () => { + const bytes = sample(260 * 1024 + 17); + const receiver = new Receiver(); + await run(receiver, bytes); + assert.deepEqual(receiver.file(), bytes); + const packets = receiver.writes.filter(bytes => bytes[0] === STX); + assert.deepEqual(packets.slice(253, 258).map(bytes => bytes[1]), [254, 255, 0, 1, 2]); + assert.equal(packets.length, 261); +}); + +test('a lost data ACK retries the identical block without duplicate progress or data', async () => { + const bytes = sample(3000); + const receiver = new Receiver({ dropDataAck: 2 }); + const progress = []; + const result = await run(receiver, bytes, { onProgress: value => progress.push(value) }); + assert.equal(result.retries, 1); + assert.equal(receiver.writes.filter(bytes => bytes[0] === STX && bytes[1] === 2).length, 2); + assert.deepEqual(receiver.file(), bytes); + assert.deepEqual(progress, [1024, 2048, 3000]); +}); + +test('NAK retries the header, a data block and the final empty header', async () => { + const rejected = new Set(); + const receiver = new Receiver({ onPacket(info, io) { + const key = `${info.phase}/${info.sequence}`; + if (!rejected.has(key)) { + rejected.add(key); + io.enqueue(Uint8Array.of(NAK)); + return true; + } + } }); + const bytes = sample(1300); + const result = await run(receiver, bytes); + assert.equal(result.retries, 4); + assert.deepEqual(receiver.file(), bytes); +}); + +test('a U-Boot C retry request is handled without mistaking it for a data ACK', async () => { + let rejected = false; + const receiver = new Receiver({ onPacket(info, io) { + if (info.phase === 'data' && !rejected) { + rejected = true; + io.enqueue(Uint8Array.of(C)); + return true; + } + } }); + const result = await run(receiver, sample(500)); + assert.equal(result.retries, 1); + assert.deepEqual(receiver.file(), sample(500)); +}); + +test('repeated NAK reaches the retry limit and does not advance to the next block', async () => { + const receiver = new Receiver({ onPacket(info, io) { + if (info.phase === 'data') { + io.enqueue(Uint8Array.of(NAK)); + return true; + } + } }); + await assert.rejects(run(receiver, sample(2000), { maxRetries: 2 }), { code: 'YMODEM_RETRIES' }); + const dataPackets = receiver.writes.filter(bytes => bytes[0] === STX); + assert.equal(dataPackets.length, 3); + assert.ok(dataPackets.every(bytes => bytes[1] === 1)); + assert.equal(receiver.eots, 0); + assert.equal(receiver.cancels, 1); +}); + +test('remote cancellation during data aborts immediately without EOT', async () => { + const receiver = new Receiver({ onPacket(info, io) { + if (info.phase === 'data') { + io.enqueue(Uint8Array.of(CAN, CAN)); + return true; + } + } }); + await assert.rejects(run(receiver, sample(2000)), { code: 'YMODEM_CANCELLED' }); + assert.equal(receiver.writes.filter(bytes => bytes[0] === STX).length, 1); + assert.equal(receiver.eots, 0); +}); + +test('an isolated CAN in noise is not a remote cancellation', async () => { + const receiver = new Receiver({ initial: [CAN, 0x0d, C] }); + await run(receiver, sample(50)); + assert.equal(receiver.phase, 'complete'); +}); + +test('abort during an outstanding read sends CAN with no aborted signal and leaves no read', async () => { + const controller = new AbortController(); + const receiver = new Receiver({ onPacket(info) { + if (info.phase === 'data') { + setTimeout(() => controller.abort(), 5); + return true; + } + } }); + await assert.rejects(run(receiver, sample(2000), { signal: controller.signal }), { name: 'AbortError' }); + assert.equal(receiver.pending, undefined); + assert.equal(receiver.cancels, 1); + assert.equal(receiver.eots, 0); + assert.ok(receiver.writes.at(-1).subarray(0, 4).every(byte => byte === CAN)); +}); + +test('an already aborted operation never touches the transport', async () => { + const controller = new AbortController(); + controller.abort(); + const receiver = new Receiver(); + await assert.rejects(run(receiver, sample(1), { signal: controller.signal }), { name: 'AbortError' }); + assert.equal(receiver.writes.length, 0); + assert.deepEqual(receiver.remaining(), Uint8Array.of(C)); +}); + +test('startup and final-header waits have deadlines', async t => { + await t.test('no initial C', async () => { + const receiver = new Receiver({ initial: [] }); + await assert.rejects(run(receiver, sample(50), { startupTimeoutMs: 20 }), { code: 'TIMEOUT' }); + assert.equal(receiver.pending, undefined); + assert.equal(receiver.writes.filter(bytes => bytes[0] === SOH).length, 0); + }); + await t.test('no final ACK', async () => { + const receiver = new Receiver({ onPacket: info => info.phase === 'final' }); + await assert.rejects(run(receiver, sample(50), { maxRetries: 1, responseTimeoutMs: 20 }), { code: 'YMODEM_RETRIES' }); + assert.equal(receiver.pending, undefined); + assert.equal(receiver.phase, 'final'); + }); +}); + +test('the overall deadline bounds retries even when each local deadline is longer', async () => { + const receiver = new Receiver({ onPacket: info => info.phase === 'data' }); + const deadlines = []; + const readByte = receiver.readByte.bind(receiver); + receiver.readByte = (deadline, signal) => { + deadlines.push(deadline); + return readByte(deadline, signal); + }; + const start = Date.now(); + await assert.rejects(run(receiver, sample(2000), { + transferTimeoutMs: 25, responseTimeoutMs: 1000, maxRetries: 100 + }), { code: 'YMODEM_TIMEOUT' }); + assert.ok(Date.now() - start < 500); + assert.ok(deadlines.every(deadline => deadline <= deadlines[0]), 'retries cannot extend the initial overall deadline'); + const packets = receiver.writes.filter(bytes => bytes[0] === STX); + assert.ok(packets.length >= 1); + // A timer may fire just before its millisecond deadline on Node 22. A + // bounded retry is allowed, but it must not advance to an unacknowledged + // packet or reset the overall deadline. + assert.ok(packets.every(bytes => bytes[1] === 1)); +}); + +test('constant unexpected input is bounded instead of extending the wait', async () => { + const receiver = new Receiver({ initial: Array(4200).fill(0x41) }); + await assert.rejects(run(receiver, sample(50)), { code: 'YMODEM_PROTOCOL' }); + assert.equal(receiver.writes.filter(bytes => bytes[0] === SOH).length, 0); +}); + +test('legacy checksum mode is rejected before any file data', async () => { + const receiver = new Receiver({ initial: [NAK] }); + await assert.rejects(run(receiver, sample(50)), { code: 'YMODEM_CHECKSUM' }); + assert.equal(receiver.writes.filter(bytes => bytes[0] === SOH).length, 0); +}); + +test('a cleanup failure preserves the original connection failure', async () => { + const original = Object.assign(new Error('USB disconnected'), { code: 'DISCONNECTED' }); + const io = { + readByte: async () => { throw original; }, + writeBytes: async () => { throw new Error('Cleanup failed'); } + }; + await assert.rejects(run(io, sample(50)), error => error === original); +}); + +test('invalid data, filenames and timeouts are rejected before transfer', async () => { + const receiver = new Receiver(); + for (const [bytes, options] of [ + [new Uint8Array(0), {}], + [sample(1), { filename: 'bad\nreset' }], + [sample(1), { filename: '../firmware.image' }], + [sample(1), { filename: 'x'.repeat(97) }], + [sample(1), { responseTimeoutMs: Infinity }], + [sample(1), { maxRetries: -1 }] + ]) await assert.rejects(run(receiver, bytes, options), { code: 'YMODEM_INPUT' }); + assert.equal(receiver.writes.length, 0); +}); + +test('invalid transport bytes cannot be mistaken for a valid response', async () => { + const io = { readByte: async () => undefined, writeBytes: async () => {} }; + await assert.rejects(run(io, sample(1)), { code: 'YMODEM_IO' }); +});