v3.28.0: the batch CAP install
The bulk workflow: one .cap and one set of install parameters applied to card after card - swap cards and each one installs as soon as it is equipped. The server owns the loop, so closing the tab or reloading the page does not interrupt it. The install chain is now shared: _ram_install_plan(body) builds the card-independent part (the parsed .cap, the INSTALL/LOAD sequence, the block size, the transport knobs) and _ram_install_run(server, body, plan, scc) runs one chain (the per-card preset/keyset/counter resolution included); the /api/ram-install handler is the plan + run + response, and the batch worker calls the same pair. The plan is built once at Start, so a bad .cap or parameter combination is a 400 there (a malformed archive included - a zip parse error is the caller's, never a dropped connection), not a per-card failure. _op_keyset_resolve() is the module form of the handler's _op_keyset() (the dead _keyset_guard method is gone). The worker (_ram_batch_worker, state _RAM_BATCH) polls the card state every 0.5 s and acts on a new card session while connected; a card already equipped at Start installs immediately. Per card the preset is matched by ICCID and its ISD role TAR supplies the keyset (v3.26.0) and the counter seed (v3.20.0); a card with no readable ICCID, no matching preset or no usable ISD keyset is recorded as skipped with its reason. A card is attempted once per run (any outcome): re-equipping it records "already processed in this batch (<outcome>)" and never installs again - restarting the batch is the retry. Failures carry the failing step and the remote SW, are never retried and never stop the run; an unexpected card-handling error is recorded and the loop keeps waiting. Endpoints: POST /api/ram-batch/start (no card needed; 400/409), GET /api/ram-batch/status (card-free - the panel polls it during an install), POST /api/ram-batch/stop (the first _CARD_FREE_POST: it only sets a flag, so the button works while the worker holds the card lock; a running install always finishes first) and POST /api/ram-batch/clear (409 while active). /api/status carries the ram_batch summary (the detailed state minus the attempts list), so the panel's headline - the live phase, the current card, the counts - rides the 2 s poll; the attempts report (the last 500 kept, the total counted) is fetched only when it changed. The batch and a test run exclude each other (409 both ways); the state is in memory - a server restart ends a run. PWA: the Batch install (.cap file, per card) RAM operation shares the install form (ramInstallCapFields(); the single install uses it too and now sends ram_format, and the block-size validation moved before the modal), hides the preset selector + Execute and the preset-mismatch banner, and renders Start/Stop/Clear, the phase headline (equip the next card / installing card + live step / stopping after the current card), the counts and the attempts table (newest first). The panel only works inside the visible SCP80 RAM pill. Docs: help EN/RU, api.md (a section + the four table rows), the repo AGENTS. Tests: the state/report helpers, the per-card decisions, the worker loop (a real thread + a fake install), the lifecycle and guards, the HTTP endpoints (the malformed .cap, the stop under a held card lock, the test-run refusal) and the PWA panel helpers/wiring. 914 frontend + 919 Python; sw cache simple-v438.
This commit is contained in:
@@ -323,6 +323,7 @@
|
||||
<tbody>
|
||||
<tr class="border-b border-gray-200 dark:border-slate-700"><td class="py-1 px-2">Обзор карты (все данные GP)</td><td class="py-1 px-2">Запрос GET STATUS для ISD, приложений, ELF и модулей ELF, а также GET DATA FF21 (расширенные ресурсы карты: число установленных приложений и свободная энергонезависимая/энергозависимая память). Компактный листинг содержит только AID, состояние жизненного цикла и привилегии (версии в устаревшем формате нет); если карта отвергает его (<code class="font-mono text-sm">P2.b2=0</code>, устаревший по GP), запросы повторяются в расширенном формате <code class="font-mono text-sm">E3</code>, а флажок <strong>Запрашивать расширенные данные реестра (связи load-файла и SD)</strong> дополнительно запрашивает их и объединяет расширенные поля: версию исполняемого load-файла, AID load-файла, AID Security Domain, списки модулей, пункты меню STK апплета (SCP Registry Data, TS 102 226 8.2.1.6) и любые другие объекты реестра, которые вернула карта (показываются как есть, без потерь) — он стоит несколько дополнительных защищённых пакетов на каждый обзор и <strong>включён по умолчанию</strong> (запоминается в браузере; снимите флажок, чтобы пропустить). Карты различаются в том, что принимают, поэтому расширенный запрос пробуется в трёх формах — эталонный список тегов (с <code class="font-mono text-sm">EA</code> по TS 102 226), тот же список без <code class="font-mono text-sm">EA</code> и вовсе без списка тегов (форма GlobalPlatformPro) — а обзор сообщает, какая форма сработала и где выполнен откат к компактному списку (версии пакетов тогда недоступны). Если строки ELF всё ещё без версий, формы со списком тегов повторяются для обоих P1=10 и P1=20, пропуская уже отклонённые комбинации, и обход останавливается, как только версия найдена. Результаты отображаются в обзоре (строка успеха минимальна, счётчики — в заголовках разделов) с кнопками <strong>Удалить</strong> для каждого элемента и определённым форматом команд RAM (подсказка при наведении объясняет compact и expanded).</td></tr>
|
||||
<tr><td class="py-1 px-2">Установка пакета (.cap файл)</td><td class="py-1 px-2">Отправка <code class="font-mono text-sm">.cap</code> файла на карту через сервер: INSTALL[for load] → LOAD ×N → INSTALL[for install (+make selectable)]. Load-файл делится на LOAD APDU размера <strong>размер блока LOAD</strong> (1–240 байт полезной нагрузки, по умолчанию 240); каждый защищённый пакет доставляется одним SMS или, если он больше, конкатенированной SMS-PP загрузкой до 5 сегментов, так что большой <code>.cap</code> просто занимает несколько SMS. Сразу после выбора файл проверяется и в форме показывается <strong>оценка требований к памяти</strong>: <strong>требование NVRAM</strong> (образ кода + постоянные данные, сумма в стиле C6+C8 из GP Card Spec) и оценка RAM. Там же показаны <strong>библиотеки, с которыми слинкован CAP</strong> (его компонент Import: имя библиотеки, AID и минимальная версия <code class="font-mono text-sm">≥ x.y</code> — имена стандартных библиотек и семейства подставляются, а где известно, даётся подсказка о версии Java Card), идентификаторы пакета и апплетов и разбивка по компонентам (размеры и доли в порядке load-файла) — всё сгруппировано по разделам <strong>Package</strong>, <strong>Requires</strong>, <strong>Memory</strong> и <strong>Components</strong>. Строка <strong>Platform</strong> показывает минимальный уровень Java Card, который должна предоставить карта (выводится из импорта <code class="font-mono text-sm">javacard.framework</code>; флаг <code class="font-mono text-sm">int</code> в заголовке дополнительно требует поддержки int — Java Card 2.2+), и <strong>релиз ETSI</strong>, из которого пришли импорты UICC API (версия <code class="font-mono text-sm">uicc.toolkit</code> → REL-N по корпусу <code class="font-mono text-sm">sim-tools</code> в рабочем каталоге; основание показано в скобках): JCRE проверяет каждый импорт по своим пакетам при верификации load-файла (JC VM spec 4.5.2), поэтому карта со старой платформой отклоняет LOAD сразу после завершения компонента <strong>Import</strong> (в строке шага виден remote SW карты и компонент, который завершил блок, например <em>завершает Import</em>): подсказка при ошибке и попап предлагают <strong>тест совместимости CAP</strong> (в один клик — тот же <code class="font-mono text-sm">.cap</code> уже выбран), чтобы найти отсутствующий пакет и версию; меньший размер блока LOAD помогает только если блок превышает буфер карты. Повреждённый файл не проходит анализ, и <strong>Execute</strong> остаётся недоступной до успешного анализа. Оценка носит справочный характер и никогда не используется при установке: NVRAM — это образ кода плюс постоянные данные (сумма в стиле C6+C8 по GP Table 11-48; управление памятью карты, округление и запись в реестре не учитываются, а образ статических полей входит в обе части); рекомендуемый <strong>C6</strong> следует за load-файлом, а рекомендуемые квоты — это десятичные значения в байтах (шестнадцатеричное значение в скобках — это кодирование параметров установки C7/C8: C6 — энергонезависимый код, C7 — энергозависимая RAM, C8 — энергонезависимые данные).</td></tr>
|
||||
<tr class="border-b border-gray-200 dark:border-slate-700"><td class="py-1 px-2">Пакетная установка (.cap, по картам)</td><td class="py-1 px-2">Массовый сценарий: один <code class="font-mono text-sm">.cap</code> и один набор параметров установки, применяемые карта за картой. <strong>Запустить пакетную установку</strong> не требует карты — цикл ведёт сервер: он ждёт карту, устанавливает сразу после завершения equip и затем ждёт следующую. Для каждой карты <strong>пресет находится по ICCID</strong> и задаёт keyset (по умолчанию из ролевой записи ISD TAR, v3.26.0), ключи и счётчик; карта без подходящего пресета или без пригодного keyset ISD TAR отмечается и пропускается. Каждая попытка попадает в список со временем, ICCID, пресетом, вердиктом и длительностью; при ошибке показаны шаг, на котором она произошла, и удалённый статусный байт — пакетная установка никогда не повторяет попытку и не останавливается при ошибке (ошибки остаются на ваше усмотрение). Карта обрабатывается <strong>один раз за запуск</strong>: повторная установка карты даёт «уже обработана» — для повтора перезапустите пакетную установку. <strong>Остановить</strong> завершает текущую карту (прерванная цепочка LOAD может оставить полузагруженный пакет), а затем завершает запуск; <strong>Очистить</strong> удаляет отчёт завершённого запуска. Цикл работает на сервере, поэтому закрытие вкладки, переключение представлений или перезагрузка страницы его не прерывают; перезапуск сервера завершает запуск. Пакетная установка и тест-скрипт исключают друг друга.</td></tr>
|
||||
<tr class="border-b border-gray-200 dark:border-slate-700"><td class="py-1 px-2">Проверка совместимости CAP</td><td class="py-1 px-2">Отвечает на один вопрос, ничего не устанавливая: <strong>может ли эта карта удовлетворить список импортов CAP?</strong> Сервер выполняет проверку формата, INSTALL[for load] и блоки LOAD только до блока, завершающего компонент <strong>Import</strong> — именно там JCRE проверяет список импортов — и останавливается: без флага последнего блока и без INSTALL[for install], поэтому ничего не фиксируется и удалять после этого ничего не нужно. Список <strong>«Версии импортов для проверки»</strong> предзаполняется из анализа CAP: <code class="font-mono text-sm">AID=version</code> переписывает запрошенную версию импорта, <code class="font-mono text-sm">+AID=version</code> добавляет синтетический импорт (запрос возможностей карты: LOAD проходит, только если карта экспортирует этот пакет версии ≥ указанной), а <strong>«Все 0.0»</strong> снимает все требования. Использование в два шага: нажмите «Все 0.0» — если проверка проходит, причиной был список импортов; затем возвращайте по одной строке, чтобы найти пакет и версию, которых не хватает карте. Вердикт явно указывает, что проверяется только <strong>этап LOAD/импортов</strong>: этап связывания (наличие реально вызываемых API) проверяет настоящая установка на INSTALL[for install]. Запуск и результат показываются в окне (как при установке): строки шагов, вердикт и блок деталей по каждому AID — при отказе он называет раздел CAP, который покрывает неудачный блок (диапазон байтов load-файла и компоненты, и завершает ли этот блок <strong>Import</strong>), SW команды с его значением, список импортов ровно в том виде, в каком он проверялся (версии CAP, правки пробы, добавленные синтетические записи, строки без совпадений) и что означает состояние пробы; при успехе — список импортов, который прошёл проверку.</td></tr>
|
||||
<tr class="border-b border-gray-200 dark:border-slate-700"><td class="py-1 px-2">INSTALL [for install] (загруженный пакет)</td><td class="py-1 px-2">Один APDU INSTALL [for install] для уже загруженного на карту пакета (его Load File AID и Module AID, привилегии, параметры установки/STK и необязательное <em>make selectable</em>) — параметры установки можно перебирать, не удаляя и не загружая <code class="font-mono text-sm">.cap</code> заново.</td></tr>
|
||||
<tr><td class="py-1 px-2">INSTALL [for make selectable]</td><td class="py-1 px-2">Один APDU INSTALL [for make selectable] (AID экземпляра) для установленного, но невыбираемого экземпляра апплета.</td></tr>
|
||||
|
||||
@@ -322,6 +322,7 @@
|
||||
<tbody>
|
||||
<tr class="border-b border-gray-200 dark:border-slate-700"><td class="py-1 px-2">Explore Card (all GP data)</td><td class="py-1 px-2">Queries GET STATUS for ISD, Applications, ELFs, and ELF Modules, plus GET DATA FF21 (Extended Card Resources: the number of installed applications and the free non-volatile/volatile memory). The compact listing carries the AID, life cycle and privileges (the legacy format has no version); if a card rejects it (<code class="font-mono text-sm">P2.b2=0</code>, deprecated by GP) the queries are retried in the expanded <code class="font-mono text-sm">E3</code> form, and the <strong>Fetch expanded registry details (load-file / SD associations)</strong> checkbox also requests it as an extra pass and merges the expanded-only fields: the Executable Load File version, Load File AID, Security Domain AID, module lists, the applet STK menu entries (SCP Registry Data, TS 102 226 8.2.1.6) and any other registry data objects the card returns (shown raw, never dropped) — it costs a few extra secured packets per Explore and is <strong>on by default</strong> (remembered per browser; untick to skip). Cards differ in what they accept, so the expanded query is tried in three forms — the reference tag list (with the TS 102 226 <code class="font-mono text-sm">EA</code>), the same list without <code class="font-mono text-sm">EA</code>, and no tag list at all (the GlobalPlatformPro form) — and the explorer reports which form worked and where the run fell back to the compact listing (package versions are then unavailable). When the ELF rows still carry no version, the tag-list forms are retried for both P1=10 and P1=20, skipping the combinations already refused, and the walk stops as soon as a version appears. Results appear in an explorer view (the success line stays minimal; the counts are in the section headings) with per-item <strong>Delete</strong> buttons and the detected RAM command format (hover for what compact vs expanded means).</td></tr>
|
||||
<tr><td class="py-1 px-2">Install Package (.cap file)</td><td class="py-1 px-2">Sends a <code class="font-mono text-sm">.cap</code> file to the card via the server: INSTALL[for load] → LOAD ×N → INSTALL[for install (+make selectable)]. The load file is split into LOAD APDUs of the <strong>LOAD block size</strong> (1–240 bytes of payload, 240 by default); each secured packet is delivered as a single SMS or, when larger, as a concatenated SMS-PP download of up to 5 segments, so a large <code class="font-mono text-sm">.cap</code> simply takes several SMS. As soon as the file is selected it is validated and its <strong>memory requirements are estimated</strong> in the form: the <strong>NVRAM requirement</strong> (the code image + persistent data, the GlobalPlatform Card Spec C6+C8 style total) and the RAM estimate. The same box reports the <strong>libraries the CAP is linked against</strong> (its Import component: library name, AID and the minimum version <code class="font-mono text-sm">≥ x.y</code>, with standard names and families resolved and a Java Card SDK hint where known), the package/applet identity and the component breakdown (sizes and shares in load-file order) — grouped under the <strong>Package</strong>, <strong>Requires</strong>, <strong>Memory</strong> and <strong>Components</strong> headings. The <strong>Platform</strong> line names the minimum Java Card level the card must provide (derived from the <code class="font-mono text-sm">javacard.framework</code> import; the header <code class="font-mono text-sm">int</code> flag additionally requires int support, Java Card 2.2+) and the <strong>ETSI release</strong> the UICC API imports come from (<code class="font-mono text-sm">uicc.toolkit</code> version → REL-N, per the workspace <code class="font-mono text-sm">sim-tools</code> corpus; shown with its basis in brackets): the JCRE checks every import against its own packages when it verifies the load file (JC VM spec 4.5.2), so a card whose platform is older rejects the LOAD as soon as the <strong>Import</strong> component is complete (the step line carries the card's remote SW and names the component the block completed, e.g. <em>completes Import</em>): the failure hint and the popup then point at the <strong>CAP compatibility test</strong> (one click — the same <code class="font-mono text-sm">.cap</code> is still selected) to find the missing package and version; a smaller LOAD block only helps when the block exceeds the card's buffer. A corrupt or wrong-format file fails the analysis, and <strong>Execute</strong> stays disabled until a successful analysis. The estimate is informational only and is never used for installation: NVRAM is the code image plus the persistent data (the GlobalPlatform C6+C8 style total, Table 11-48 — card memory management, rounding and the registry entry are not included, and the static field image is counted in both parts); the suggested <strong>C6</strong> follows the load file, and the suggested quotas are decimal byte counts (the hex in parentheses is how the C7/C8 install parameters encode them: C6 = non-volatile code, C7 = volatile RAM, C8 = non-volatile data).</td></tr>
|
||||
<tr class="border-b border-gray-200 dark:border-slate-700"><td class="py-1 px-2">Batch install (.cap file, per card)</td><td class="py-1 px-2">The bulk workflow: one <code class="font-mono text-sm">.cap</code> and one set of install parameters, applied to card after card. <strong>Start batch</strong> needs no card — the server owns the loop: it waits for a card, installs the moment the equip finishes, then waits for the next one. Every card's <strong>preset is matched by ICCID</strong> and supplies the keyset (the ISD role TAR's default, v3.26.0), the keys and the counter; a card with no matching preset or no usable ISD keyset is reported and skipped. Each attempt lands in the list with its time, ICCID, preset, verdict and duration; a failure shows the failing step and the remote status word — the batch never retries and never stops on a failure (failures are yours to manage afterwards). A card is attempted <strong>once per run</strong>: re-equipping it reports “already processed” — restart the batch to retry it. <strong>Stop</strong> finishes the current card first (an interrupted LOAD chain can leave a half-loaded package) and then ends the run; <strong>Clear</strong> drops the finished report. The loop runs in the server, so closing the tab, switching views or reloading the page does not interrupt it; a server restart ends it. A batch and a test run exclude each other.</td></tr>
|
||||
<tr class="border-b border-gray-200 dark:border-slate-700"><td class="py-1 px-2">CAP compatibility test</td><td class="py-1 px-2">Answers one question without installing anything: <strong>can this card satisfy the CAP's import list?</strong> The server runs the format check, INSTALL[for load] and the LOAD blocks only up to the block that completes the <strong>Import</strong> component — the point where the JCRE verifies the import list — then stops: no last-block flag and no INSTALL[for install], so nothing is committed and nothing has to be deleted afterwards. The <strong>Import versions to test</strong> list is pre-filled from the CAP analysis: <code class="font-mono text-sm">AID=version</code> rewrites an import's requested version, <code class="font-mono text-sm">+AID=version</code> appends a synthetic import (a card-capability query: the LOAD passes only if the card exports that package at ≥ that version), and <strong>Set all 0.0</strong> drops every requirement. Two-step use: press Set all 0.0 — if the test passes, the import list was the blocker; then restore one line at a time to find the package and version the card lacks. The verdict states it covers the <strong>LOAD/import gate only</strong>: the link gate (whether the applet's actual API calls exist) is what a real install checks at INSTALL[for install]. The run and its result appear in a popup (like the install): the step lines, the verdict and a per-AID detail block — on a rejection it names the CAP section the failing block covers (load-file byte range and components, and whether that block completes <strong>Import</strong>), the remote status word with its meaning, the import list exactly as tested (CAP versions, probe rewrites, appended synthetic entries, unmatched lines) and what the probe state implies; on success it lists the import list that passed.</td></tr>
|
||||
<tr class="border-b border-gray-200 dark:border-slate-700"><td class="py-1 px-2">INSTALL [for install] (loaded package)</td><td class="py-1 px-2">One INSTALL [for install] APDU for a package that is already loaded on the card (its Load File AID and Module AID, privileges, install/STK parameters and an optional <em>make selectable</em>) — iterate the install parameters without deleting and re-loading the <code class="font-mono text-sm">.cap</code> every time.</td></tr>
|
||||
<tr><td class="py-1 px-2">INSTALL [for make selectable]</td><td class="py-1 px-2">One INSTALL [for make selectable] APDU (the instance AID) for an INSTALLED, non-selectable applet instance.</td></tr>
|
||||
|
||||
+265
-32
@@ -689,7 +689,7 @@
|
||||
<p class="text-xs text-gray-500 dark:text-slate-400 mb-3" data-l10n="RAM operations perform atomic GlobalPlatform commands over SCP80. Card keys are taken from the saved preset.">RAM operations perform atomic GlobalPlatform commands over SCP80. Card keys are taken from the saved preset.</p>
|
||||
|
||||
<div class="mb-3 flex gap-2 items-end">
|
||||
<div class="flex-1">
|
||||
<div id="ram-preset-cell" class="flex-1">
|
||||
<label class="block mb-1 text-sm font-medium text-gray-700 dark:text-slate-300" data-l10n="Card preset">Card preset</label>
|
||||
<select id="ram-card-sel" onchange="ramApplyCard(this.value)" class="w-full border border-gray-300 dark:border-slate-600 text-sm rounded px-3 py-1.5 dark:bg-slate-800">
|
||||
<option value="" data-l10n="— Select card —">— Select card —</option>
|
||||
@@ -700,6 +700,7 @@
|
||||
<select id="ram-op" onchange="ramOpChanged()" class="w-full border border-gray-300 dark:border-slate-600 text-sm rounded px-3 py-1.5 dark:bg-slate-800">
|
||||
<option value="explore" data-l10n="Explore Card (all GP data)">Explore Card (all GP data)</option>
|
||||
<option value="install-cap" data-l10n="Install Package (.cap file)">Install Package (.cap file)</option>
|
||||
<option value="batch" data-l10n="Batch install (.cap file, per card)">Batch install (.cap file, per card)</option>
|
||||
<option value="compat" data-l10n="CAP compatibility test">CAP compatibility test</option>
|
||||
<option value="install-app" data-l10n="INSTALL [for install] (loaded package)">INSTALL [for install] (loaded package)</option>
|
||||
<option value="make-selectable" data-l10n="INSTALL [for make selectable]">INSTALL [for make selectable]</option>
|
||||
@@ -714,7 +715,7 @@
|
||||
<option value="expanded-ae" data-l10n="Expanded (AE 80, indefinite length)">Expanded (AE 80, indefinite length)</option>
|
||||
</select>
|
||||
</div>
|
||||
<button data-needs="card" data-needs-keyset="ram" data-cap-gate="ram" onclick="ramExecute()" class="px-5 py-1.5 bg-blue-600 text-white text-sm font-medium rounded hover:bg-blue-700 disabled:opacity-40 disabled:cursor-not-allowed" data-l10n="Execute">Execute</button>
|
||||
<button id="ram-exec-btn" data-needs="card" data-needs-keyset="ram" data-cap-gate="ram" onclick="ramExecute()" class="px-5 py-1.5 bg-blue-600 text-white text-sm font-medium rounded hover:bg-blue-700 disabled:opacity-40 disabled:cursor-not-allowed" data-l10n="Execute">Execute</button>
|
||||
</div>
|
||||
<div id="ram-preset-warning" class="hidden mb-3 px-3 py-2 rounded border border-amber-400 dark:border-amber-600 bg-amber-50 dark:bg-amber-900/20 text-sm text-amber-700 dark:text-amber-300"></div>
|
||||
|
||||
@@ -912,6 +913,19 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="ram-batch-panel" class="hidden mb-3 border border-gray-200 dark:border-slate-700 rounded p-3">
|
||||
<div class="flex flex-wrap items-center gap-2 mb-2">
|
||||
<button type="button" id="ram-batch-start" data-needs="server" data-cap-gate="ram" onclick="ramBatchStart()" class="px-5 py-1.5 bg-blue-600 text-white text-sm font-medium rounded hover:bg-blue-700 disabled:opacity-40 disabled:cursor-not-allowed" data-l10n="Start batch">Start batch</button>
|
||||
<button type="button" id="ram-batch-stop" onclick="ramBatchStop()" class="hidden px-5 py-1.5 bg-red-600 text-white text-sm font-medium rounded hover:bg-red-700 disabled:opacity-40 disabled:cursor-not-allowed" data-l10n="Stop">Stop</button>
|
||||
<button type="button" id="ram-batch-clear" onclick="ramBatchClear()" class="px-3 py-1.5 text-sm rounded border border-gray-300 dark:border-slate-600 hover:bg-gray-200 dark:hover:bg-slate-700 text-gray-700 dark:text-slate-300" data-l10n="Clear">Clear</button>
|
||||
<span id="ram-batch-state" class="text-sm font-medium text-gray-700 dark:text-slate-300"></span>
|
||||
</div>
|
||||
<div id="ram-batch-notice" class="hidden mb-2 px-3 py-2 rounded border border-blue-300 dark:border-blue-800 bg-blue-50 dark:bg-blue-900/20 text-sm text-blue-700 dark:text-blue-300"></div>
|
||||
<div id="ram-batch-counts" class="text-xs text-gray-500 dark:text-slate-400 mb-2"></div>
|
||||
<div id="ram-batch-attempts" class="max-h-64 overflow-y-auto text-xs"></div>
|
||||
<div class="text-xs text-gray-400 dark:text-slate-500 mt-2" data-l10n="The preset, keyset and counter come from each card's own preset (matched by ICCID). A card is attempted once per run: re-equipping it reports it as already processed - restart the batch to retry. Stop finishes the current card first.">The preset, keyset and counter come from each card's own preset (matched by ICCID). A card is attempted once per run: re-equipping it reports it as already processed - restart the batch to retry. Stop finishes the current card first.</div>
|
||||
</div>
|
||||
|
||||
<div id="ram-result" class="mt-2 text-base font-semibold font-mono hidden"></div>
|
||||
<div id="ram-cntr-low" class="mt-2 hidden"></div>
|
||||
<div id="ram-explorer" class="mt-2 text-xs font-mono hidden"></div>
|
||||
@@ -1895,7 +1909,7 @@
|
||||
// ===== Version =====
|
||||
// Single source of truth for the PWA version: shown in the header and used
|
||||
// by the server version check in pysimConnect().
|
||||
const SIMPLE_VERSION = '3.27.0';
|
||||
const SIMPLE_VERSION = '3.28.0';
|
||||
document.getElementById('app-version').textContent = 'v' + SIMPLE_VERSION;
|
||||
|
||||
// ===== view history (the browser Back/Forward buttons) =====
|
||||
@@ -10099,7 +10113,8 @@ function ramOpChanged() {
|
||||
const op = document.getElementById('ram-op').value;
|
||||
if (_ramOpLast !== null && op !== _ramOpLast) ramClearResults();
|
||||
_ramOpLast = op;
|
||||
const isCap = op === 'install-cap';
|
||||
const isBatch = op === 'batch';
|
||||
const isCap = op === 'install-cap' || isBatch;
|
||||
const isCompat = op === 'compat';
|
||||
const isApp = op === 'install-app' || op === 'make-selectable';
|
||||
const setHidden = (id, hidden) => {
|
||||
@@ -10110,6 +10125,13 @@ function ramOpChanged() {
|
||||
setHidden('ram-cap-rows', !(isCap || isCompat));
|
||||
setHidden('ram-compat-rows', !isCompat);
|
||||
setHidden('ram-app-rows', !isApp);
|
||||
// The batch resolves the preset per card (by ICCID): its selector and the
|
||||
// single-card Execute button do not apply, and the batch panel takes over.
|
||||
setHidden('ram-preset-cell', isBatch);
|
||||
setHidden('ram-preset-warning', isBatch);
|
||||
setHidden('ram-exec-btn', isBatch);
|
||||
setHidden('ram-batch-panel', !isBatch);
|
||||
if (isBatch) ramBatchFetch();
|
||||
// The Execute button's .cap gate applies to the install-cap and compat ops.
|
||||
if (typeof pysimApplyAvailability === 'function') pysimApplyAvailability();
|
||||
}
|
||||
@@ -10124,6 +10146,217 @@ function ramHideProgress() {
|
||||
document.getElementById('ram-progress').classList.add('hidden');
|
||||
}
|
||||
|
||||
// ===== batch CAP install (v3.28.0) =====
|
||||
// The bulk workflow: the server owns the loop (a worker installs on every card
|
||||
// that gets equipped, using each card's own preset) and this panel is a thin
|
||||
// view over /api/ram-batch/status. The live headline comes from the 2 s
|
||||
// /api/status poll (the batch summary + the RAM progress); the detailed status
|
||||
// (the attempts list) is fetched only when the summary says it changed.
|
||||
let _ramBatchLast = null; // the last detailed /api/ram-batch/status
|
||||
let _ramBatchFetching = false;
|
||||
let _ramBatchSummary = null; // /api/status.ram_batch
|
||||
let _ramBatchProgress = null; // /api/status.ram_progress
|
||||
|
||||
function ramBatchPanelVisible() {
|
||||
const op = document.getElementById('ram-op');
|
||||
return isViewVisible('tab-scp80') && isViewVisible('scp80-sub-ram')
|
||||
&& !!op && op.value === 'batch';
|
||||
}
|
||||
|
||||
async function ramBatchFetch() {
|
||||
if (_ramBatchFetching) return;
|
||||
_ramBatchFetching = true;
|
||||
try {
|
||||
_ramBatchLast = await pysimFetch('/api/ram-batch/status');
|
||||
} catch (e) { /* the next poll retries */ }
|
||||
_ramBatchFetching = false;
|
||||
ramBatchRender();
|
||||
}
|
||||
|
||||
// Called from the 2 s status poll: the summary drives the headline, a change
|
||||
// in the attempts count (or the active flag) refreshes the detailed view.
|
||||
function ramBatchApplyStatus(status) {
|
||||
if (!status) return;
|
||||
_ramBatchSummary = status.ram_batch || null;
|
||||
_ramBatchProgress = status.ram_progress || null;
|
||||
if (!ramBatchPanelVisible()) return;
|
||||
const total = _ramBatchSummary ? (_ramBatchSummary.attempts_total || 0) : 0;
|
||||
const active = _ramBatchSummary ? !!_ramBatchSummary.active : false;
|
||||
if (!_ramBatchLast || (_ramBatchLast.attempts_total || 0) !== total
|
||||
|| !!_ramBatchLast.active !== active) {
|
||||
ramBatchFetch();
|
||||
return;
|
||||
}
|
||||
ramBatchRender();
|
||||
}
|
||||
|
||||
function ramBatchRender() {
|
||||
const panel = document.getElementById('ram-batch-panel');
|
||||
if (!panel) return;
|
||||
if (!ramBatchPanelVisible()) {
|
||||
panel.classList.add('hidden');
|
||||
return;
|
||||
}
|
||||
panel.classList.remove('hidden');
|
||||
// The summary (the 2 s status poll) is fresher than the last detailed
|
||||
// fetch: it carries the phase/current/notice/counts, the attempts list
|
||||
// comes from the detailed status.
|
||||
const st = Object.assign({ active: false, phase: 'idle', attempts: [], counts: {} },
|
||||
_ramBatchLast || {}, _ramBatchSummary || {});
|
||||
const active = !!st.active;
|
||||
const phase = st.phase || (active ? 'waiting_card' : 'idle');
|
||||
const startBtn = document.getElementById('ram-batch-start');
|
||||
if (startBtn) startBtn.classList.toggle('hidden', active);
|
||||
const stopBtn = document.getElementById('ram-batch-stop');
|
||||
if (stopBtn) {
|
||||
stopBtn.classList.toggle('hidden', !active);
|
||||
stopBtn.textContent = phase === 'stopping' ? t('Stopping...') : t('Stop');
|
||||
stopBtn.disabled = phase === 'stopping';
|
||||
}
|
||||
const stateEl = document.getElementById('ram-batch-state');
|
||||
if (stateEl) {
|
||||
if (!active) {
|
||||
stateEl.textContent = phase === 'stopped' ? t('Batch stopped')
|
||||
: (phase === 'finished' ? t('Batch finished') : '');
|
||||
} else if (phase === 'installing') {
|
||||
const cur = st.current || {};
|
||||
stateEl.textContent = t('Installing...') + ' ' + (cur.iccid || '')
|
||||
+ (cur.preset ? ' \u2014 ' + cur.preset : '');
|
||||
} else if (phase === 'stopping') {
|
||||
stateEl.textContent = t('Stopping after the current card...');
|
||||
} else {
|
||||
stateEl.textContent = t('Waiting for a card...');
|
||||
}
|
||||
}
|
||||
const notice = document.getElementById('ram-batch-notice');
|
||||
if (notice) {
|
||||
notice.textContent = st.notice || '';
|
||||
notice.classList.toggle('hidden', !st.notice);
|
||||
}
|
||||
const counts = document.getElementById('ram-batch-counts');
|
||||
if (counts) {
|
||||
const c = st.counts || {};
|
||||
let text = t('Installed') + ': ' + (c.installed || 0)
|
||||
+ ' \u00b7 ' + t('Failed') + ': ' + (c.failed || 0)
|
||||
+ ' \u00b7 ' + t('Skipped') + ': ' + (c.skipped || 0);
|
||||
if (st.attempts_total) text += ' \u00b7 ' + st.attempts_total + ' ' + t('attempts');
|
||||
if (active && _ramBatchProgress && _ramBatchProgress.active && _ramBatchProgress.name) {
|
||||
// the step name already carries its index for the LOAD steps
|
||||
text += ' \u00b7 ' + _ramBatchProgress.name;
|
||||
}
|
||||
counts.textContent = text;
|
||||
}
|
||||
const box = document.getElementById('ram-batch-attempts');
|
||||
if (box) box.innerHTML = ramBatchAttemptsHtml(st.attempts || []);
|
||||
}
|
||||
|
||||
function ramBatchAttemptsHtml(attempts) {
|
||||
if (!attempts.length) return '<div class="text-gray-400 dark:text-slate-500">' + esc(t('No cards processed yet.')) + '</div>';
|
||||
let html = '<table class="w-full"><tbody>';
|
||||
for (let i = attempts.length - 1; i >= 0; i--) {
|
||||
const a = attempts[i];
|
||||
const when = a.ts ? new Date(a.ts * 1000).toLocaleTimeString() : '';
|
||||
const verdict = a.result === 'installed' ? t('OK')
|
||||
: (a.result === 'failed' ? t('Failed') : t('Skipped'));
|
||||
const tone = a.result === 'installed' ? 'text-emerald-600 dark:text-emerald-400'
|
||||
: (a.result === 'failed' ? 'text-red-600 dark:text-red-400' : 'text-amber-600 dark:text-amber-400');
|
||||
const detail = a.result === 'failed'
|
||||
? [a.failed_step, a.por_sw || a.sw].filter(Boolean).join(' \u2014 ')
|
||||
: (a.reason || '');
|
||||
html += '<tr class="border-b border-gray-100 dark:border-slate-800">'
|
||||
+ '<td class="py-0.5 pr-2 text-gray-400 dark:text-slate-500 whitespace-nowrap">' + esc(when) + '</td>'
|
||||
+ '<td class="py-0.5 pr-2 font-mono whitespace-nowrap">' + esc(a.iccid || '') + '</td>'
|
||||
+ '<td class="py-0.5 pr-2">' + esc(a.preset || '') + '</td>'
|
||||
+ '<td class="py-0.5 pr-2 font-medium whitespace-nowrap ' + tone + '">' + esc(verdict) + '</td>'
|
||||
+ '<td class="py-0.5 pr-2 text-gray-500 dark:text-slate-400">' + esc(detail) + '</td>'
|
||||
+ '<td class="py-0.5 text-gray-400 dark:text-slate-500 whitespace-nowrap text-right">'
|
||||
+ (a.duration_ms ? (a.duration_ms / 1000).toFixed(1) + ' s' : '') + '</td>'
|
||||
+ '</tr>';
|
||||
}
|
||||
return html + '</tbody></table>';
|
||||
}
|
||||
|
||||
// The .cap + install parameters shared by the single install and the batch:
|
||||
// everything except the per-card preset/keyset/counter fields, which the
|
||||
// server resolves from each card's own preset. Returns null after alerting
|
||||
// when a value is unusable (the caller stops before opening a modal).
|
||||
function ramInstallCapFields() {
|
||||
// The STK hex is regenerated on every toolkit field edit; recompute it
|
||||
// once more at send time unless the user pasted a custom hex directly
|
||||
// (dataset.manual), so the sent parameters always match the fields.
|
||||
const stkEl = document.getElementById('ram-stk-params');
|
||||
if (document.getElementById('rc-toolkit-enable').checked && !(stkEl.dataset && stkEl.dataset.manual)) {
|
||||
updateStkParamsHex();
|
||||
}
|
||||
// The privileges are an aggregate of the checkboxes: derive them now, so a
|
||||
// value restored by the browser or left from an earlier experiment can
|
||||
// never be sent silently.
|
||||
updateRcPriv();
|
||||
const composed = ramInstallParamsCompose();
|
||||
const body = {
|
||||
sd_aid: (document.getElementById('ram-sd-aid').value || '').replace(/[^0-9a-fA-F]/g, ''),
|
||||
privileges: (document.getElementById('rc-priv').value || '00').replace(/[^0-9a-fA-F]/g, ''),
|
||||
install_params: composed.install_params,
|
||||
stk_params: composed.stk_params,
|
||||
make_selectable: document.getElementById('ram-make-sel').checked,
|
||||
ram_format: (document.getElementById('ram-format') || {}).value || 'auto',
|
||||
};
|
||||
const loadSize = (document.getElementById('ram-load-size').value || '').trim();
|
||||
if (loadSize !== '') {
|
||||
const n = parseInt(loadSize, 10);
|
||||
if (!(n >= 1 && n <= 240)) { alert(t('LOAD block size must be 1..240')); return null; }
|
||||
body.load_block_size = n;
|
||||
}
|
||||
return body;
|
||||
}
|
||||
|
||||
async function ramBatchStart() {
|
||||
if (!capGateOk('ram')) { alert(t('Analyze the CAP file first')); return; }
|
||||
const fileInput = document.getElementById('ram-cap-file');
|
||||
const file = fileInput.files[0];
|
||||
if (!file) { alert(t('Select a .cap file')); return; }
|
||||
if (file.size > 48 * 1024) { alert(t('CAP file exceeds 48 kB limit')); return; }
|
||||
const fields = ramInstallCapFields();
|
||||
if (!fields) return;
|
||||
const startBtn = document.getElementById('ram-batch-start');
|
||||
if (startBtn) startBtn.disabled = true;
|
||||
try {
|
||||
fields.cap_hex = await ramReadFileHex(file);
|
||||
_ramBatchLast = await pysimFetchOk('/api/ram-batch/start', fields);
|
||||
_ramBatchSummary = null;
|
||||
} catch (e) {
|
||||
alert(t('Error') + ': ' + e.message);
|
||||
} finally {
|
||||
if (startBtn) startBtn.disabled = false;
|
||||
if (typeof pysimApplyAvailability === 'function') pysimApplyAvailability();
|
||||
ramBatchRender();
|
||||
}
|
||||
}
|
||||
|
||||
async function ramBatchStop() {
|
||||
const stopBtn = document.getElementById('ram-batch-stop');
|
||||
if (stopBtn) stopBtn.disabled = true;
|
||||
try {
|
||||
_ramBatchLast = await pysimFetchOk('/api/ram-batch/stop', {});
|
||||
_ramBatchSummary = null; // the poll refreshes it; the fresh detail wins
|
||||
} catch (e) {
|
||||
alert(t('Error') + ': ' + e.message);
|
||||
} finally {
|
||||
ramBatchRender();
|
||||
}
|
||||
}
|
||||
|
||||
async function ramBatchClear() {
|
||||
try {
|
||||
await pysimFetchOk('/api/ram-batch/clear', {});
|
||||
_ramBatchLast = null;
|
||||
_ramBatchSummary = null;
|
||||
ramBatchFetch();
|
||||
} catch (e) {
|
||||
alert(t('Error') + ': ' + e.message);
|
||||
}
|
||||
}
|
||||
|
||||
// ===== RAM operation modal (v3.6.34) =====
|
||||
// Long RAM operations (install chains, Explore) run behind a modal that blocks
|
||||
// everything else - an interrupted install can leave a half-loaded package.
|
||||
@@ -12441,6 +12674,10 @@ async function ramInstallCap(sp) {
|
||||
const file = fileInput.files[0];
|
||||
if (!file) { alert(t('Select a .cap file')); return; }
|
||||
if (file.size > 48 * 1024) { alert(t('CAP file exceeds 48 kB limit')); return; }
|
||||
// The parameters are validated before the modal opens (an unusable block
|
||||
// size must not leave a modal whose Close is disabled).
|
||||
const fields = ramInstallCapFields();
|
||||
if (!fields) return;
|
||||
|
||||
const capPkg = (_capAnalysis.ram.memory && _capAnalysis.ram.memory.package_aid) || '';
|
||||
ramOpModalBegin(t('Installing package') + (capPkg ? ' \u2014 ' + capPkg : ''));
|
||||
@@ -12448,36 +12685,12 @@ async function ramInstallCap(sp) {
|
||||
const capHex = await ramReadFileHex(file);
|
||||
ramOpModalStatus(t('Sending to server for install...'));
|
||||
|
||||
// The STK hex is regenerated on every toolkit field edit; recompute it
|
||||
// once more at send time unless the user pasted a custom hex directly
|
||||
// (dataset.manual), so the sent parameters always match the fields.
|
||||
const stkEl = document.getElementById('ram-stk-params');
|
||||
if (document.getElementById('rc-toolkit-enable').checked && !(stkEl.dataset && stkEl.dataset.manual)) {
|
||||
updateStkParamsHex();
|
||||
}
|
||||
// The privileges are an aggregate of the checkboxes: derive them now, so a
|
||||
// value restored by the browser or left from an earlier experiment can
|
||||
// never be sent silently.
|
||||
updateRcPriv();
|
||||
|
||||
const composed = ramInstallParamsCompose();
|
||||
const body = {
|
||||
const body = Object.assign({
|
||||
cap_hex: capHex,
|
||||
preset_id: sp.preset_id,
|
||||
sd_aid: (document.getElementById('ram-sd-aid').value || '').replace(/[^0-9a-fA-F]/g, ''),
|
||||
privileges: (document.getElementById('rc-priv').value || '00').replace(/[^0-9a-fA-F]/g, ''),
|
||||
install_params: composed.install_params,
|
||||
stk_params: composed.stk_params,
|
||||
make_selectable: document.getElementById('ram-make-sel').checked,
|
||||
spi1: sp.spi1, spi2: '01', kic: sp.kic, kid: sp.kid,
|
||||
tar: sp.tar, cntr: sp.cntr, kicKey: sp.kicKey, kidKey: sp.kidKey,
|
||||
};
|
||||
const loadSize = (document.getElementById('ram-load-size').value || '').trim();
|
||||
if (loadSize !== '') {
|
||||
const n = parseInt(loadSize, 10);
|
||||
if (!(n >= 1 && n <= 240)) { alert(t('LOAD block size must be 1..240')); return; }
|
||||
body.load_block_size = n;
|
||||
}
|
||||
}, fields);
|
||||
|
||||
const data = await pysimFetch('/api/ram-install', body);
|
||||
|
||||
@@ -13810,7 +14023,11 @@ function spPresetWarningRender() {
|
||||
el.classList.toggle('hidden', !text);
|
||||
};
|
||||
show('sp-preset-warning', spPresetWarning(iccid, cards, spPresetIdx()));
|
||||
show('ram-preset-warning', spPresetWarning(iccid, cards, ramPresetIdx()));
|
||||
// The batch resolves the preset per card, so the RAM view's warning does
|
||||
// not apply there (v3.28.0).
|
||||
const ramOp = document.getElementById('ram-op');
|
||||
const batchMode = !!ramOp && ramOp.value === 'batch';
|
||||
show('ram-preset-warning', batchMode ? '' : spPresetWarning(iccid, cards, ramPresetIdx()));
|
||||
show('tar-preset-warning', spPresetWarning(iccid, cards, tarPresetIdx()));
|
||||
}
|
||||
|
||||
@@ -17130,7 +17347,10 @@ function pysimStartBackendPoll() {
|
||||
_pysimCardSession = null;
|
||||
_pysimStatusTimer = setInterval(async () => {
|
||||
try {
|
||||
pysimCardStateUpdate(await pysimFetch('/api/status'));
|
||||
const status = await pysimFetch('/api/status');
|
||||
// The batch panel's live headline rides this poll (v3.28.0).
|
||||
ramBatchApplyStatus(status);
|
||||
pysimCardStateUpdate(status);
|
||||
} catch (e) {
|
||||
pysimSetServerAvailable(false);
|
||||
}
|
||||
@@ -24182,6 +24402,19 @@ const LANG_RU = {
|
||||
'Loading...': 'Загрузка...',
|
||||
'Close': 'Закрыть',
|
||||
'Installing package': 'Установка пакета',
|
||||
'Batch install (.cap file, per card)': 'Пакетная установка (.cap, по картам)',
|
||||
'Start batch': 'Запустить пакетную установку',
|
||||
'Stopping...': 'Остановка…',
|
||||
'Batch stopped': 'Пакетная установка остановлена',
|
||||
'Batch finished': 'Пакетная установка завершена',
|
||||
'Installing...': 'Установка…',
|
||||
'Stopping after the current card...': 'Остановка после текущей карты…',
|
||||
'Waiting for a card...': 'Ожидание карты…',
|
||||
'Installed': 'Установлено',
|
||||
'Skipped': 'Пропущено',
|
||||
'attempts': 'попыток',
|
||||
'No cards processed yet.': 'Карты ещё не обрабатывались.',
|
||||
'The preset, keyset and counter come from each card\'s own preset (matched by ICCID). A card is attempted once per run: re-equipping it reports it as already processed - restart the batch to retry. Stop finishes the current card first.': 'Пресет, keyset и счётчик берутся из пресета каждой карты (совпадение по ICCID). Карта обрабатывается один раз за запуск: повторная установка карты отмечается как уже обработанная — для повтора перезапустите пакетную установку. «Остановить» завершает текущую карту.',
|
||||
'Do not close or reload this window while the operation is running.': 'Не закрывайте и не перезагружайте окно, пока операция выполняется.',
|
||||
'Working...': 'Выполняется...',
|
||||
'APDU hex': 'APDU (hex)',
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
const CACHE = 'simple-v437';
|
||||
const CACHE = 'simple-v438';
|
||||
const URLS = [
|
||||
'index.html',
|
||||
'help.html',
|
||||
|
||||
@@ -591,8 +591,10 @@ test('every tab-content lives inside the max-w-7xl page container', () => {
|
||||
});
|
||||
|
||||
test('the RAM form shows Card preset and Operation in one row', () => {
|
||||
const row = /<div class="mb-3 flex gap-2 items-end">\s*<div class="flex-1">\s*<label[^>]*data-l10n="Card preset"[\s\S]*?id="ram-card-sel"[\s\S]*?data-l10n="Operation"[\s\S]*?id="ram-op"[\s\S]*?data-l10n="Execute"/.exec(html);
|
||||
const row = /<div class="mb-3 flex gap-2 items-end">\s*<div id="ram-preset-cell" class="flex-1">\s*<label[^>]*data-l10n="Card preset"[\s\S]*?id="ram-card-sel"[\s\S]*?data-l10n="Operation"[\s\S]*?id="ram-op"[\s\S]*?data-l10n="Execute"/.exec(html);
|
||||
assert.ok(row, 'Card preset + Operation + Execute must share one row');
|
||||
// the batch mode hides the preset cell and Execute (per-card resolution)
|
||||
assert.match(html, /setHidden\('ram-preset-cell', isBatch\)/);
|
||||
});
|
||||
|
||||
test('the RAM operation modal is wide enough for the step lines', () => {
|
||||
|
||||
@@ -79,5 +79,6 @@ test('both SCP80 views carry the warning banner', () => {
|
||||
// the preset selection
|
||||
assert.ok(html.includes('spPresetWarningRender();'));
|
||||
assert.ok(html.includes("show('sp-preset-warning', spPresetWarning(iccid, cards, spPresetIdx()));"));
|
||||
assert.ok(html.includes("show('ram-preset-warning', spPresetWarning(iccid, cards, ramPresetIdx()));"));
|
||||
// the batch resolves the preset per card: the RAM banner is suppressed there
|
||||
assert.ok(html.includes("batchMode ? '' : spPresetWarning(iccid, cards, ramPresetIdx())"));
|
||||
});
|
||||
|
||||
@@ -0,0 +1,251 @@
|
||||
const { test } = require('node:test');
|
||||
const assert = require('node:assert');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
|
||||
const html = fs.readFileSync(path.join(__dirname, '..', 'index.html'), 'utf8');
|
||||
|
||||
function extractFunc(src, name, asyncFn) {
|
||||
const re = new RegExp('function\\s+' + name + '\\s*\\([^)]*\\)\\s*\\{');
|
||||
const m = re.exec(src);
|
||||
if (!m) throw new Error('function ' + name + ' not found');
|
||||
let i = m.index + m[0].length - 1;
|
||||
let depth = 0;
|
||||
for (; i < src.length; i++) {
|
||||
if (src[i] === '{') depth++;
|
||||
else if (src[i] === '}') {
|
||||
depth--;
|
||||
if (depth === 0) break;
|
||||
}
|
||||
}
|
||||
return (asyncFn ? 'async ' : '') + src.slice(m.index, i + 1);
|
||||
}
|
||||
|
||||
const ASYNC_FNS = ['ramBatchFetch', 'ramBatchStart', 'ramBatchStop', 'ramBatchClear'];
|
||||
let code = '';
|
||||
for (const fn of ['ramBatchPanelVisible', 'ramBatchAttemptsHtml', 'ramBatchRender',
|
||||
'ramBatchApplyStatus', 'ramBatchFetch', 'ramBatchStart', 'ramBatchStop',
|
||||
'ramBatchClear', 'esc']) {
|
||||
code += extractFunc(html, fn, ASYNC_FNS.indexOf(fn) >= 0) + '\n';
|
||||
}
|
||||
|
||||
const els = {};
|
||||
function setEl(id, value) {
|
||||
els[id] = {
|
||||
id: id, value: value === undefined ? '' : value, textContent: '', innerHTML: '',
|
||||
disabled: false,
|
||||
classes: {},
|
||||
classList: {
|
||||
add(c) { els[id].classes[c] = true; },
|
||||
remove(c) { delete els[id].classes[c]; },
|
||||
toggle(c, on) { if (on) els[id].classes[c] = true; else delete els[id].classes[c]; },
|
||||
contains(c) { return !!els[id].classes[c]; },
|
||||
},
|
||||
};
|
||||
return els[id];
|
||||
}
|
||||
function clearEls() {
|
||||
for (const k of Object.keys(els)) delete els[k];
|
||||
}
|
||||
|
||||
const app = new Function('els', `
|
||||
var sandbox = { fetched: [], replies: {}, fetchError: null, alerts: [], visibility: true };
|
||||
var document = { getElementById: id => els[id] || null };
|
||||
var t = k => k;
|
||||
var isViewVisible = () => sandbox.visibility;
|
||||
var alert = m => sandbox.alerts.push(String(m));
|
||||
var pysimFetch = async (p) => { sandbox.fetched.push(p); return sandbox.replies[p] || null; };
|
||||
var pysimFetchOk = async (p, body) => {
|
||||
sandbox.fetched.push(p);
|
||||
sandbox.bodies = sandbox.bodies || {};
|
||||
sandbox.bodies[p] = body;
|
||||
if (sandbox.fetchError) throw new Error(sandbox.fetchError);
|
||||
return sandbox.replies[p] || { ok: true };
|
||||
};
|
||||
var capGateOk = () => sandbox.capGate !== false;
|
||||
var ramReadFileHex = async () => 'AABB';
|
||||
var ramInstallCapFields = () => ({ sd_aid: '', install_params: '', ram_format: 'auto' });
|
||||
var pysimApplyAvailability = () => {};
|
||||
var _ramBatchLast = null;
|
||||
var _ramBatchFetching = false;
|
||||
var _ramBatchSummary = null;
|
||||
var _ramBatchProgress = null;
|
||||
${code}
|
||||
sandbox.getLast = () => _ramBatchLast;
|
||||
sandbox.setLast = v => { _ramBatchLast = v; };
|
||||
sandbox.getSummary = () => _ramBatchSummary;
|
||||
sandbox.getProgress = () => _ramBatchProgress;
|
||||
sandbox.ramBatchPanelVisible = ramBatchPanelVisible;
|
||||
sandbox.ramBatchAttemptsHtml = ramBatchAttemptsHtml;
|
||||
sandbox.ramBatchRender = ramBatchRender;
|
||||
sandbox.ramBatchApplyStatus = ramBatchApplyStatus;
|
||||
sandbox.ramBatchFetch = ramBatchFetch;
|
||||
sandbox.ramBatchStart = ramBatchStart;
|
||||
sandbox.ramBatchStop = ramBatchStop;
|
||||
sandbox.ramBatchClear = ramBatchClear;
|
||||
return sandbox;
|
||||
`)(els);
|
||||
|
||||
test('the RAM view wires the batch operation and the panel', () => {
|
||||
assert.match(html, /<option value="batch" data-l10n="Batch install \(\.cap file, per card\)">/);
|
||||
assert.match(html, /<div id="ram-batch-panel"/);
|
||||
for (const id of ['ram-batch-start', 'ram-batch-stop', 'ram-batch-clear',
|
||||
'ram-batch-state', 'ram-batch-notice', 'ram-batch-counts', 'ram-batch-attempts']) {
|
||||
assert.match(html, new RegExp('id="' + id + '"'));
|
||||
}
|
||||
// the batch start needs the server (not a card) and the CAP analysis
|
||||
assert.match(html, /id="ram-batch-start" data-needs="server" data-cap-gate="ram"/);
|
||||
assert.match(html, /'Batch install \(\.cap file, per card\)': /);
|
||||
});
|
||||
|
||||
test('ramOpChanged hides the preset cell and Execute in batch mode', () => {
|
||||
const src = extractFunc(html, 'ramOpChanged');
|
||||
assert.match(src, /const isBatch = op === 'batch';/);
|
||||
assert.match(src, /const isCap = op === 'install-cap' \|\| isBatch;/);
|
||||
assert.match(src, /setHidden\('ram-preset-cell', isBatch\)/);
|
||||
assert.match(src, /setHidden\('ram-exec-btn', isBatch\)/);
|
||||
assert.match(src, /setHidden\('ram-batch-panel', !isBatch\)/);
|
||||
assert.match(src, /if \(isBatch\) ramBatchFetch\(\);/);
|
||||
// the preset warning does not apply to the per-card resolution
|
||||
const warn = extractFunc(html, 'spPresetWarningRender');
|
||||
assert.match(warn, /batchMode \? '' : spPresetWarning/);
|
||||
});
|
||||
|
||||
test('the status poll drives the batch panel', () => {
|
||||
const poll = extractFunc(html, 'pysimStartBackendPoll');
|
||||
assert.match(poll, /const status = await pysimFetch\('\/api\/status'\);/);
|
||||
assert.match(poll, /ramBatchApplyStatus\(status\);/);
|
||||
// the single install and the batch share the field builder
|
||||
const inst = extractFunc(html, 'ramInstallCap', true);
|
||||
assert.match(inst, /const fields = ramInstallCapFields\(\);/);
|
||||
assert.match(inst, /Object\.assign\(\{/);
|
||||
const start = extractFunc(html, 'ramBatchStart', true);
|
||||
assert.match(start, /ramInstallCapFields\(\)/);
|
||||
assert.match(start, /pysimFetchOk\('\/api\/ram-batch\/start', fields\)/);
|
||||
});
|
||||
|
||||
test('ramBatchAttemptsHtml renders every verdict with its detail', () => {
|
||||
const out = app.ramBatchAttemptsHtml([
|
||||
{ ts: 1700000000, iccid: '8970119000004600098', preset: 'Alfa', result: 'installed', duration_ms: 12000 },
|
||||
{ ts: 1700000001, iccid: '8970119000004600106', preset: 'Alfa', result: 'failed',
|
||||
failed_step: 'LOAD (3/7)', por_sw: '6A80', duration_ms: 9000 },
|
||||
{ ts: 1700000002, iccid: '8970119000004600114', result: 'skipped',
|
||||
reason: 'no preset matches this ICCID' },
|
||||
]);
|
||||
assert.match(out, /8970119000004600098/);
|
||||
assert.match(out, /OK/);
|
||||
assert.match(out, /LOAD \(3\/7\) — 6A80/);
|
||||
assert.match(out, /no preset matches this ICCID/);
|
||||
assert.match(out, /12\.0 s/);
|
||||
// newest first
|
||||
assert.ok(out.indexOf('8970119000004600114') < out.indexOf('8970119000004600098'));
|
||||
assert.match(app.ramBatchAttemptsHtml([]), /No cards processed yet\./);
|
||||
});
|
||||
|
||||
test('ramBatchRender shows the phase, the counts and the stop button', () => {
|
||||
clearEls();
|
||||
setEl('ram-op', 'batch');
|
||||
setEl('ram-batch-panel', '');
|
||||
setEl('ram-batch-start', '');
|
||||
setEl('ram-batch-stop', '');
|
||||
setEl('ram-batch-state', '');
|
||||
setEl('ram-batch-notice', '');
|
||||
setEl('ram-batch-counts', '');
|
||||
setEl('ram-batch-attempts', '');
|
||||
// waiting for a card
|
||||
app.setLast({ active: true, phase: 'waiting_card', attempts: [], counts: {}, attempts_total: 0, notice: '' });
|
||||
app.ramBatchRender();
|
||||
assert.strictEqual(els['ram-batch-state'].textContent, 'Waiting for a card...');
|
||||
assert.ok(els['ram-batch-stop'].classes['hidden'] === undefined);
|
||||
assert.ok(els['ram-batch-start'].classes['hidden']);
|
||||
// installing card X with the live step
|
||||
app.setLast({ active: true, phase: 'installing', attempts: [], counts: { installed: 2, failed: 1, skipped: 0 },
|
||||
attempts_total: 3, notice: 'Card 897… installed.', current: { iccid: '8970119000004600098', preset: 'Alfa' } });
|
||||
app.ramBatchRender();
|
||||
assert.match(els['ram-batch-state'].textContent, /Installing\.\.\. 8970119000004600098 — Alfa/);
|
||||
assert.match(els['ram-batch-counts'].textContent, /Installed: 2 · Failed: 1 · Skipped: 0 · 3 attempts/);
|
||||
assert.strictEqual(els['ram-batch-notice'].textContent, 'Card 897… installed.');
|
||||
// stopping
|
||||
app.setLast({ active: true, phase: 'stopping', attempts: [], counts: {}, attempts_total: 0 });
|
||||
app.ramBatchRender();
|
||||
assert.match(els['ram-batch-state'].textContent, /Stopping after the current card\.\.\./);
|
||||
assert.strictEqual(els['ram-batch-stop'].textContent, 'Stopping...');
|
||||
assert.ok(els['ram-batch-stop'].disabled);
|
||||
// stopped
|
||||
app.setLast({ active: false, phase: 'stopped', attempts: [], counts: {}, attempts_total: 0 });
|
||||
app.ramBatchRender();
|
||||
assert.strictEqual(els['ram-batch-state'].textContent, 'Batch stopped');
|
||||
assert.ok(els['ram-batch-start'].classes['hidden'] === undefined);
|
||||
assert.ok(els['ram-batch-stop'].classes['hidden']);
|
||||
});
|
||||
|
||||
test('ramBatchApplyStatus fetches only when the summary changed', async () => {
|
||||
clearEls();
|
||||
setEl('ram-op', 'batch');
|
||||
setEl('ram-batch-panel', '');
|
||||
setEl('ram-batch-start', '');
|
||||
setEl('ram-batch-stop', '');
|
||||
setEl('ram-batch-state', '');
|
||||
setEl('ram-batch-notice', '');
|
||||
setEl('ram-batch-counts', '');
|
||||
setEl('ram-batch-attempts', '');
|
||||
app.fetched = [];
|
||||
app.replies['/api/ram-batch/status'] = { active: true, phase: 'waiting_card', attempts: [], counts: {}, attempts_total: 1 };
|
||||
app.ramBatchApplyStatus({ ram_batch: { active: true, phase: 'waiting_card', attempts_total: 1, installed: 0, failed: 0, skipped: 0 } });
|
||||
await new Promise(r => setImmediate(r));
|
||||
assert.deepStrictEqual(app.fetched, ['/api/ram-batch/status']);
|
||||
// an unchanged summary does not refetch
|
||||
app.ramBatchApplyStatus({ ram_batch: { active: true, phase: 'waiting_card', attempts_total: 1 } });
|
||||
await new Promise(r => setImmediate(r));
|
||||
assert.strictEqual(app.fetched.length, 1);
|
||||
// a new attempt refetches
|
||||
app.ramBatchApplyStatus({ ram_batch: { active: true, phase: 'waiting_card', attempts_total: 2 } });
|
||||
await new Promise(r => setImmediate(r));
|
||||
assert.strictEqual(app.fetched.length, 2);
|
||||
// the panel is not visible -> no fetch, no render
|
||||
clearEls();
|
||||
app.fetched = [];
|
||||
app.ramBatchApplyStatus({ ram_batch: { active: true, attempts_total: 5 } });
|
||||
await new Promise(r => setImmediate(r));
|
||||
assert.deepStrictEqual(app.fetched, []);
|
||||
});
|
||||
|
||||
test('the panel headline follows the live summary (phase and step)', () => {
|
||||
clearEls();
|
||||
setEl('ram-op', 'batch');
|
||||
setEl('ram-batch-panel', '');
|
||||
setEl('ram-batch-start', '');
|
||||
setEl('ram-batch-stop', '');
|
||||
setEl('ram-batch-state', '');
|
||||
setEl('ram-batch-notice', '');
|
||||
setEl('ram-batch-counts', '');
|
||||
setEl('ram-batch-attempts', '');
|
||||
// the detailed status is stale (waiting), the 2 s summary says installing
|
||||
app.setLast({ active: true, phase: 'waiting_card', attempts: [], counts: {}, attempts_total: 0 });
|
||||
app.ramBatchApplyStatus({
|
||||
ram_batch: { active: true, phase: 'installing', attempts_total: 0,
|
||||
current: { iccid: '8970119000004600098', preset: 'Alfa' },
|
||||
counts: { installed: 0, failed: 0, skipped: 0 } },
|
||||
ram_progress: { active: true, step: 3, total: 8, name: 'LOAD (3/7)' },
|
||||
});
|
||||
assert.match(els['ram-batch-state'].textContent, /Installing\.\.\. 8970119000004600098 — Alfa/);
|
||||
assert.match(els['ram-batch-counts'].textContent, /LOAD \(3\/7\)/);
|
||||
// ...and back to waiting when the card is gone
|
||||
app.ramBatchApplyStatus({ ram_batch: { active: true, phase: 'waiting_card', attempts_total: 0,
|
||||
counts: { installed: 0, failed: 0, skipped: 0 } } });
|
||||
assert.strictEqual(els['ram-batch-state'].textContent, 'Waiting for a card...');
|
||||
});
|
||||
|
||||
test('the stop and clear calls hit their endpoints', async () => {
|
||||
clearEls();
|
||||
app.fetched = [];
|
||||
app.replies['/api/ram-batch/stop'] = { active: true, phase: 'stopping', attempts: [], counts: {}, attempts_total: 0 };
|
||||
app.replies['/api/ram-batch/clear'] = { ok: true };
|
||||
app.replies['/api/ram-batch/status'] = { active: false, phase: 'idle', attempts: [], counts: {}, attempts_total: 0 };
|
||||
setEl('ram-op', 'batch');
|
||||
setEl('ram-batch-panel', '');
|
||||
await app.ramBatchStop();
|
||||
await app.ramBatchClear();
|
||||
await new Promise(r => setImmediate(r));
|
||||
assert.deepStrictEqual(app.fetched, ['/api/ram-batch/stop', '/api/ram-batch/clear', '/api/ram-batch/status']);
|
||||
});
|
||||
@@ -57,12 +57,19 @@ test('updateRcPriv aggregates the checked privilege boxes', () => {
|
||||
});
|
||||
|
||||
test('the install derives the privileges at send time', () => {
|
||||
const fn = extractFunc(html, 'ramInstallCap');
|
||||
// v3.28.0: the shared field builder (the single install and the batch) does
|
||||
// the derivation before it returns the body
|
||||
const fn = extractFunc(html, 'ramInstallCapFields');
|
||||
const iPriv = fn.indexOf('updateRcPriv();');
|
||||
const iBody = fn.indexOf('const body = {');
|
||||
assert.ok(iPriv >= 0, 'ramInstallCap must call updateRcPriv()');
|
||||
assert.ok(iBody >= 0, 'ramInstallCap body not found');
|
||||
assert.ok(iPriv >= 0, 'ramInstallCapFields must call updateRcPriv()');
|
||||
assert.ok(iBody >= 0, 'ramInstallCapFields body not found');
|
||||
assert.ok(iPriv < iBody, 'the privileges must be derived before the request body');
|
||||
// both callers go through it
|
||||
assert.ok(/ramInstallCapFields\(\)/.test(extractFunc(html, 'ramInstallCap')),
|
||||
'ramInstallCap must use the shared field builder');
|
||||
assert.ok(/ramInstallCapFields\(\)/.test(extractFunc(html, 'ramBatchStart')),
|
||||
'ramBatchStart must use the shared field builder');
|
||||
});
|
||||
|
||||
test('the form resets the restored grants on load', () => {
|
||||
|
||||
@@ -207,7 +207,8 @@ test('updateStkParamsHex names the rejection reason', () => {
|
||||
});
|
||||
|
||||
test('the install body composes the C9/quota prefix', () => {
|
||||
const fn = extractFunc(html, 'ramInstallCap');
|
||||
// v3.28.0: the shared field builder (the single install and the batch)
|
||||
const fn = extractFunc(html, 'ramInstallCapFields');
|
||||
assert.ok(/const composed = ramInstallParamsCompose\(\)/.test(fn), fn);
|
||||
assert.ok(/install_params: composed\.install_params/.test(fn), fn);
|
||||
assert.ok(/stk_params: composed\.stk_params/.test(fn), fn);
|
||||
|
||||
Reference in New Issue
Block a user