diff --git a/docs/api.md b/docs/api.md index 9bc34ff..3e958d1 100644 --- a/docs/api.md +++ b/docs/api.md @@ -46,6 +46,10 @@ a 3.x PWA). | `/api/help` | POST | pySim help for a given command | | `/api/send-ota` | POST | SCP80 OTA secured packet delivery | | `/api/ram-install` | POST | Install a Java Card `.cap` file via SCP80 (INSTALL[for load] → LOAD ×N → INSTALL[for install]) | +| `/api/ram-batch/start` | POST | Start the **batch CAP install** (v3.28.0): the server installs the same `.cap` on every card that gets equipped, using each card's preset (matched by ICCID) | +| `/api/ram-batch/status` | GET | The batch state: phase, current card, counts and the attempts report (card-free) | +| `/api/ram-batch/stop` | POST | Stop the batch — a running install finishes first (card-free, so it works while the install holds the card lock) | +| `/api/ram-batch/clear` | POST | Drop the finished batch's report (`409` while a batch is active) | | `/api/ram-install-app` | POST | Single INSTALL [for install] / [for make selectable] for an already loaded package (no re-load) | | `/api/cap-info` | POST | Validate a `.cap` archive and estimate its code/NVRAM/RAM requirements (read-only) | | `/api/cap-compat` | POST | CAP compatibility test: LOAD only to the block completing the Import component (nothing committed) | @@ -1126,6 +1130,68 @@ sets `success: false`, `failed_step` and a detailed `error` such as The `steps` array contains one entry per GP command. `final_cntr` is the counter value after all successful steps (use it to update the card preset). The response is not streamed — all steps run server-side before the JSON is returned. +### `POST /api/ram-batch/start`, `GET /api/ram-batch/status`, `POST /api/ram-batch/stop`, `POST /api/ram-batch/clear` + +The **batch CAP install** (v3.28.0): one `.cap` and one set of install +parameters applied to card after card, for bulk provisioning. The loop runs +**in the server** (a worker thread), so a page reload or a closed tab does not +interrupt it; the state lives in memory and a server restart ends the run. + +- `POST /api/ram-batch/start` — the body is the `/api/ram-install` payload + **without** the per-card fields (`preset_id`, `tar`, `spi1`, `cntr`, + `kic`/`kid`/`kicKey`/`kidKey`): the plan is card independent and is built + once, so a bad `.cap` or an invalid parameter combination is a `400` at + Start, not a per-card failure. **No card is needed** — the worker waits for + one. `400` for a bad request, `409` when another batch or a test run is + active. The response is the status payload below plus `ok: true`. +- `GET /api/ram-batch/status` — **card-free** (the panel polls it while an + install holds the card lock): + +```json +{"active": true, "phase": "waiting_card", + "attempts": [{"ts": 1760000000.0, "iccid": "8970119000004600098", + "preset": "Batch 0002", "result": "installed", + "duration_ms": 41230, "final_cntr": "0000000005", + "load_file_aid": "F0414C46416101", + "module_aid": "F0414C4641610101", "nv_delta": 3120}], + "attempts_total": 3, + "current": null, "notice": "Card 8970119000004600098 installed.", + "counts": {"installed": 2, "failed": 1, "skipped": 0}, + "started": 1760000000.0, "stopped": null, "progress": null} +``` + + `phase` is `idle` (no run), `waiting_card`, `installing`, `stopping`, + `stopped` or `finished`. A failed attempt carries `failed_step` (e.g. + `LOAD (3/7)`), `por_sw` (the card's own status word), `por_status`, + `por_error` and `sw`; a skipped one carries `reason`. `current` names the + card being installed (`{iccid, preset, started}`) and `progress` mirrors the + RAM progress payload while a chain runs. The report keeps the last 500 + attempts (`attempts_total` counts them all). +- `POST /api/ram-batch/stop` — sets the stop flag: a running install finishes + first (an interrupted LOAD chain can leave a half-loaded package), then the + run ends. It touches no card state, so it answers while the card lock is + held (a `_CARD_FREE_POST` exception); a repeated stop is idempotent, `409` + when no run exists. +- `POST /api/ram-batch/clear` — drops the finished run's report (`409` while a + batch is active). + +**Per-card resolution.** Every equipped card's **preset is matched by +ICCID**; the preset's ISD role TAR supplies the keyset (v3.26.0), the keys and +the counter seed (v3.20.0) — the same rules as `/api/ram-install`. A card +with no readable ICCID, no matching preset or no usable ISD keyset is recorded +as `skipped` with its reason and the batch keeps waiting. A card is attempted +**once per run** (any outcome): re-equipping it is recorded as +`already processed in this batch ()`, never installed again — +restart the batch to retry it. Failures never stop the run and are never +retried automatically. + +`/api/status` carries a small summary in `ram_batch` — the detailed state +**minus the attempts list** (`{active, phase, current, notice, +attempts_total, counts, started, stopped}`), so the panel's headline (the +phase, the current card, the counts) rides the existing 2 s status poll; the +attempts report is fetched from `/api/ram-batch/status` only when +`attempts_total` (or the active flag) changed. + ### `POST /api/ram-install-app` Run the single **INSTALL [for install]** (or **INSTALL [for make selectable]**) APDU for an *already loaded* package — one APDU, so the install parameters can be iterated without deleting and re-loading the `.cap`. The APDU builders are shared with `/api/ram-install` (`_cap_install_apdu` / `_cap_make_selectable_apdu`; both case 3 — no trailing `Le`, which the card's SCP80 layer counts as a phantom command) and the step verdict/counter logic is the same (`final_cntr` is returned on success **and** on failure). diff --git a/frontend/help-ru.html b/frontend/help-ru.html index fb1b7b0..3f94b82 100644 --- a/frontend/help-ru.html +++ b/frontend/help-ru.html @@ -323,6 +323,7 @@ Обзор карты (все данные GP)Запрос GET STATUS для ISD, приложений, ELF и модулей ELF, а также GET DATA FF21 (расширенные ресурсы карты: число установленных приложений и свободная энергонезависимая/энергозависимая память). Компактный листинг содержит только AID, состояние жизненного цикла и привилегии (версии в устаревшем формате нет); если карта отвергает его (P2.b2=0, устаревший по GP), запросы повторяются в расширенном формате E3, а флажок Запрашивать расширенные данные реестра (связи load-файла и SD) дополнительно запрашивает их и объединяет расширенные поля: версию исполняемого load-файла, AID load-файла, AID Security Domain, списки модулей, пункты меню STK апплета (SCP Registry Data, TS 102 226 8.2.1.6) и любые другие объекты реестра, которые вернула карта (показываются как есть, без потерь) — он стоит несколько дополнительных защищённых пакетов на каждый обзор и включён по умолчанию (запоминается в браузере; снимите флажок, чтобы пропустить). Карты различаются в том, что принимают, поэтому расширенный запрос пробуется в трёх формах — эталонный список тегов (с EA по TS 102 226), тот же список без EA и вовсе без списка тегов (форма GlobalPlatformPro) — а обзор сообщает, какая форма сработала и где выполнен откат к компактному списку (версии пакетов тогда недоступны). Если строки ELF всё ещё без версий, формы со списком тегов повторяются для обоих P1=10 и P1=20, пропуская уже отклонённые комбинации, и обход останавливается, как только версия найдена. Результаты отображаются в обзоре (строка успеха минимальна, счётчики — в заголовках разделов) с кнопками Удалить для каждого элемента и определённым форматом команд RAM (подсказка при наведении объясняет compact и expanded). Установка пакета (.cap файл)Отправка .cap файла на карту через сервер: INSTALL[for load] → LOAD ×N → INSTALL[for install (+make selectable)]. Load-файл делится на LOAD APDU размера размер блока LOAD (1–240 байт полезной нагрузки, по умолчанию 240); каждый защищённый пакет доставляется одним SMS или, если он больше, конкатенированной SMS-PP загрузкой до 5 сегментов, так что большой .cap просто занимает несколько SMS. Сразу после выбора файл проверяется и в форме показывается оценка требований к памяти: требование NVRAM (образ кода + постоянные данные, сумма в стиле C6+C8 из GP Card Spec) и оценка RAM. Там же показаны библиотеки, с которыми слинкован CAP (его компонент Import: имя библиотеки, AID и минимальная версия ≥ x.y — имена стандартных библиотек и семейства подставляются, а где известно, даётся подсказка о версии Java Card), идентификаторы пакета и апплетов и разбивка по компонентам (размеры и доли в порядке load-файла) — всё сгруппировано по разделам Package, Requires, Memory и Components. Строка Platform показывает минимальный уровень Java Card, который должна предоставить карта (выводится из импорта javacard.framework; флаг int в заголовке дополнительно требует поддержки int — Java Card 2.2+), и релиз ETSI, из которого пришли импорты UICC API (версия uicc.toolkit → REL-N по корпусу sim-tools в рабочем каталоге; основание показано в скобках): JCRE проверяет каждый импорт по своим пакетам при верификации load-файла (JC VM spec 4.5.2), поэтому карта со старой платформой отклоняет LOAD сразу после завершения компонента Import (в строке шага виден remote SW карты и компонент, который завершил блок, например завершает Import): подсказка при ошибке и попап предлагают тест совместимости CAP (в один клик — тот же .cap уже выбран), чтобы найти отсутствующий пакет и версию; меньший размер блока LOAD помогает только если блок превышает буфер карты. Повреждённый файл не проходит анализ, и Execute остаётся недоступной до успешного анализа. Оценка носит справочный характер и никогда не используется при установке: NVRAM — это образ кода плюс постоянные данные (сумма в стиле C6+C8 по GP Table 11-48; управление памятью карты, округление и запись в реестре не учитываются, а образ статических полей входит в обе части); рекомендуемый C6 следует за load-файлом, а рекомендуемые квоты — это десятичные значения в байтах (шестнадцатеричное значение в скобках — это кодирование параметров установки C7/C8: C6 — энергонезависимый код, C7 — энергозависимая RAM, C8 — энергонезависимые данные). + Пакетная установка (.cap, по картам)Массовый сценарий: один .cap и один набор параметров установки, применяемые карта за картой. Запустить пакетную установку не требует карты — цикл ведёт сервер: он ждёт карту, устанавливает сразу после завершения equip и затем ждёт следующую. Для каждой карты пресет находится по ICCID и задаёт keyset (по умолчанию из ролевой записи ISD TAR, v3.26.0), ключи и счётчик; карта без подходящего пресета или без пригодного keyset ISD TAR отмечается и пропускается. Каждая попытка попадает в список со временем, ICCID, пресетом, вердиктом и длительностью; при ошибке показаны шаг, на котором она произошла, и удалённый статусный байт — пакетная установка никогда не повторяет попытку и не останавливается при ошибке (ошибки остаются на ваше усмотрение). Карта обрабатывается один раз за запуск: повторная установка карты даёт «уже обработана» — для повтора перезапустите пакетную установку. Остановить завершает текущую карту (прерванная цепочка LOAD может оставить полузагруженный пакет), а затем завершает запуск; Очистить удаляет отчёт завершённого запуска. Цикл работает на сервере, поэтому закрытие вкладки, переключение представлений или перезагрузка страницы его не прерывают; перезапуск сервера завершает запуск. Пакетная установка и тест-скрипт исключают друг друга. Проверка совместимости CAPОтвечает на один вопрос, ничего не устанавливая: может ли эта карта удовлетворить список импортов CAP? Сервер выполняет проверку формата, INSTALL[for load] и блоки LOAD только до блока, завершающего компонент Import — именно там JCRE проверяет список импортов — и останавливается: без флага последнего блока и без INSTALL[for install], поэтому ничего не фиксируется и удалять после этого ничего не нужно. Список «Версии импортов для проверки» предзаполняется из анализа CAP: AID=version переписывает запрошенную версию импорта, +AID=version добавляет синтетический импорт (запрос возможностей карты: LOAD проходит, только если карта экспортирует этот пакет версии ≥ указанной), а «Все 0.0» снимает все требования. Использование в два шага: нажмите «Все 0.0» — если проверка проходит, причиной был список импортов; затем возвращайте по одной строке, чтобы найти пакет и версию, которых не хватает карте. Вердикт явно указывает, что проверяется только этап LOAD/импортов: этап связывания (наличие реально вызываемых API) проверяет настоящая установка на INSTALL[for install]. Запуск и результат показываются в окне (как при установке): строки шагов, вердикт и блок деталей по каждому AID — при отказе он называет раздел CAP, который покрывает неудачный блок (диапазон байтов load-файла и компоненты, и завершает ли этот блок Import), SW команды с его значением, список импортов ровно в том виде, в каком он проверялся (версии CAP, правки пробы, добавленные синтетические записи, строки без совпадений) и что означает состояние пробы; при успехе — список импортов, который прошёл проверку. INSTALL [for install] (загруженный пакет)Один APDU INSTALL [for install] для уже загруженного на карту пакета (его Load File AID и Module AID, привилегии, параметры установки/STK и необязательное make selectable) — параметры установки можно перебирать, не удаляя и не загружая .cap заново. INSTALL [for make selectable]Один APDU INSTALL [for make selectable] (AID экземпляра) для установленного, но невыбираемого экземпляра апплета. diff --git a/frontend/help.html b/frontend/help.html index 63dd047..4386882 100644 --- a/frontend/help.html +++ b/frontend/help.html @@ -322,6 +322,7 @@ Explore Card (all GP data)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 (P2.b2=0, deprecated by GP) the queries are retried in the expanded E3 form, and the Fetch expanded registry details (load-file / SD associations) 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 on by default (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 EA), the same list without EA, 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 Delete buttons and the detected RAM command format (hover for what compact vs expanded means). Install Package (.cap file)Sends a .cap 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 LOAD block size (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 .cap simply takes several SMS. As soon as the file is selected it is validated and its memory requirements are estimated in the form: the NVRAM requirement (the code image + persistent data, the GlobalPlatform Card Spec C6+C8 style total) and the RAM estimate. The same box reports the libraries the CAP is linked against (its Import component: library name, AID and the minimum version ≥ x.y, 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 Package, Requires, Memory and Components headings. The Platform line names the minimum Java Card level the card must provide (derived from the javacard.framework import; the header int flag additionally requires int support, Java Card 2.2+) and the ETSI release the UICC API imports come from (uicc.toolkit version → REL-N, per the workspace sim-tools 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 Import component is complete (the step line carries the card's remote SW and names the component the block completed, e.g. completes Import): the failure hint and the popup then point at the CAP compatibility test (one click — the same .cap 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 Execute 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 C6 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). + Batch install (.cap file, per card)The bulk workflow: one .cap and one set of install parameters, applied to card after card. Start batch 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 preset is matched by ICCID 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 once per run: re-equipping it reports “already processed” — restart the batch to retry it. Stop finishes the current card first (an interrupted LOAD chain can leave a half-loaded package) and then ends the run; Clear 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. CAP compatibility testAnswers one question without installing anything: can this card satisfy the CAP's import list? The server runs the format check, INSTALL[for load] and the LOAD blocks only up to the block that completes the Import 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 Import versions to test list is pre-filled from the CAP analysis: AID=version rewrites an import's requested version, +AID=version appends a synthetic import (a card-capability query: the LOAD passes only if the card exports that package at ≥ that version), and Set all 0.0 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 LOAD/import gate only: 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 Import), 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. INSTALL [for install] (loaded package)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 make selectable) — iterate the install parameters without deleting and re-loading the .cap every time. INSTALL [for make selectable]One INSTALL [for make selectable] APDU (the instance AID) for an INSTALLED, non-selectable applet instance. diff --git a/frontend/index.html b/frontend/index.html index cc080d0..dcd0e95 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -689,7 +689,7 @@

RAM operations perform atomic GlobalPlatform commands over SCP80. Card keys are taken from the saved preset.

-
+
+ @@ -714,7 +715,7 @@
- +
@@ -912,6 +913,19 @@
+ + @@ -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 '
' + esc(t('No cards processed yet.')) + '
'; + let html = ''; + 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 += '' + + '' + + '' + + '' + + '' + + '' + + '' + + ''; + } + return html + '
' + esc(when) + '' + esc(a.iccid || '') + '' + esc(a.preset || '') + '' + esc(verdict) + '' + esc(detail) + '' + + (a.duration_ms ? (a.duration_ms / 1000).toFixed(1) + ' s' : '') + '
'; +} + +// 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)', diff --git a/frontend/sw.js b/frontend/sw.js index ed0f071..ea18a98 100644 --- a/frontend/sw.js +++ b/frontend/sw.js @@ -1,4 +1,4 @@ -const CACHE = 'simple-v437'; +const CACHE = 'simple-v438'; const URLS = [ 'index.html', 'help.html', diff --git a/frontend/tests/html.test.js b/frontend/tests/html.test.js index 3b03bad..5a2298c 100644 --- a/frontend/tests/html.test.js +++ b/frontend/tests/html.test.js @@ -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 = /
\s*
\s*]*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 = /
\s*
\s*]*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', () => { diff --git a/frontend/tests/preset_warning.test.js b/frontend/tests/preset_warning.test.js index 2a50a82..f6c47ab 100644 --- a/frontend/tests/preset_warning.test.js +++ b/frontend/tests/preset_warning.test.js @@ -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())")); }); diff --git a/frontend/tests/ram_batch.test.js b/frontend/tests/ram_batch.test.js new file mode 100644 index 0000000..28a9752 --- /dev/null +++ b/frontend/tests/ram_batch.test.js @@ -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, /