From cdd38200645b841880798cd023605dfa21f64148 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BD=D1=82=D0=BE=D0=BD=20=D0=A2=D1=80=D0=BE=D1=88?= =?UTF-8?q?=D0=B8=D0=BD?= Date: Wed, 21 Oct 2026 13:20:28 +0300 Subject: [PATCH] v3.32.1: "Start counter value" in the outfile import The import created presets with the store's default counter (1). Cards whose counters are already past it had to be edited preset by preset afterwards. - The outfile preview form gains a "Start counter value" field (default 1, the store's value). The value is written into every created keyset of every imported card - parse_outfile's `start_counter`, 1-10 hex digits, whitespace stripped and uppercased; a bad value raises and the endpoint answers 400. Without it the store's default still applies (the field is omitted), so the API keeps its old behaviour. - The preview shows the counter; an import stores the protocol's 10-digit form (counter_hex). - Docs: api.md (the field), help EN/RU (the form). - Version strings + the PWA cache bumped together (simple-v459). Tests: the parser (every keyset, normalisation, unset, the bad values), the endpoint (the preview's keysets, the 400, the stored padded form), the PWA (the field's default, the controls' normalisation, both bodies). 1008 Python + 953 frontend green. --- CHANGELOG.md | 9 +++++++++ docs/api.md | 4 ++++ frontend/help-ru.html | 2 +- frontend/help.html | 2 +- frontend/index.html | 18 ++++++++++++++---- frontend/sw.js | 2 +- frontend/tests/cards_outfile.test.js | 10 ++++++++-- pyproject.toml | 2 +- pysim_simple_server/outfile.py | 25 +++++++++++++++++++------ pysim_simple_server/server.py | 5 +++-- tests/test_fetch_routes.py | 20 ++++++++++++++++++++ tests/test_outfile.py | 20 ++++++++++++++++++++ 12 files changed, 101 insertions(+), 18 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 45d8af8..b714250 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,15 @@ every change carries a descriptive commit message. ## [Unreleased] +## [3.32.1] — 2026-10-21 + +### Added + +- **"Start counter value"** in the outfile import: the counter every created keyset + starts from. It defaults to the store's value (`1`); raise it for cards whose + counters are already past it. The API takes `start_counter` (1–10 hex digits; + a bad value is a 400), and the preview carries the value. + ## [3.32.0] — 2026-10-21 ### Added diff --git a/docs/api.md b/docs/api.md index 03fb45c..8e1624a 100644 --- a/docs/api.md +++ b/docs/api.md @@ -351,6 +351,10 @@ into a preview. - `tar_keyset` — an optional **global default keyset** (1–15) for the TAR entries that do not name one (the API's shorthand; the PWA sends per-row keysets instead). +- `start_counter` — the counter **every created keyset starts from** (1–10 hex + digits; whitespace stripped, uppercased). Without it the store's default + (`1`) applies. A bad value is a `400`; the import stores the protocol's + 10-digit form. Recognised columns (case-insensitive): `ICCID` (the digits + odd-nibble F pad, the plain digits, spaced digits or the raw nibble-swapped EF hex all diff --git a/frontend/help-ru.html b/frontend/help-ru.html index 541451c..ee5faf4 100644 --- a/frontend/help-ru.html +++ b/frontend/help-ru.html @@ -372,7 +372,7 @@
Столбец SCP81 показывает, задана ли в пресете рабочая пара PSK: ✓ (зелёный) — идентификатор и ключ заданы; ⚠ (жёлтый) — задано только одно из двух, и слушатель такой пресет игнорирует; — — PSK нет. Идентификатор и ключ PSK задаются вместе. Кнопка Добавить пресет открывает редактор с новым пресетом; Редактировать загружает пресет строки в редактор, поэтому поля можно менять без повторного ввода карты; Сохранить сохраняет и возвращает к списку, Отмена отменяет правки; Удалить удаляет строку (только в списке). Обмен пресетами: Экспорт в файл для выгрузки и Импорт из файла для загрузки. Выбранный пресет автоматически заполняет форму Secured Packet и устанавливает TAR для операции (RAM/GP → ISD TAR, SIM RFM → UICC RFM TAR, USIM RFM → ADF RFM TAR); TAR, введённый в форму Secured Packet вручную, сохраняется при отправке - счётчик, ключи и MSL этого TAR по-прежнему берутся из пресета; SPI1 берётся из MSL, а меньшее значение даёт предупреждение (сервер тоже возвращает его как warning); изменения сразу передаются работающему слушателю SCP81.
Импорт outfile загружает сразу много карт из outfile поставщика карт — текстового дампа инструмента персонализации: шапка с баннером и параметрами, затем разделённая пробелами строка колонок (среди токенов есть ICCID; первый токен может нести префикс вида var_out:) и по одной строке на карту. Всё до строки колонок и все неиспользуемые колонки игнорируются. Каждая строка данных должна содержать значение для каждой объявленной колонки — формат позиционный, поэтому пустое значение неотличимо от отсутствующего — а пара KICn/KIDn, объявленная в заголовке, должна иметь пригодное значение в каждой строке; нарушение делает весь файл некорректным (предпросмотр называет строку, импорт отклоняется). Разбираются ICCID (цифры, цифры с добивочным F до чётного числа нибблов, цифры с разделителями или сырой hex EF — всё приводится к одной форме), PIN1/PIN2/PUK1/PUK2, ADM (hex-значение ключа, 4–16 hex-цифр (чётное число) — например 3632333239463337), PSK (16 байт; необязательная колонка PSKID/PSK_ID задаёт её идентификатор, по умолчанию берётся ICCID карты) и нумерованные пары ключей KICn/KIDn — по одному keyset на пару, до 15. Байтов KIc/KID в файле нет: номер keyset — это номер колонки (KIC2 → keyset 2), а ниббл алгоритма определяется размером ключа — 8 байт DES, 24 байта 3DES3, а для 16 байт — выбором в предпросмотре: 3DES2 (по умолчанию) или AES; любой другой размер пропускает этот keyset с пометкой. TAR также не берутся из файла: предпросмотр показывает таблицу TAR, которую получат импортируемые карты (по умолчанию три ролевые записи с TAR по спецификации и MSL 16; их можно править, кнопка + TAR добавляет записи), и у каждой строки свой keyset — список из найденных в файле keysets (первый выбран заранее; при ненулевом MSL keyset обязателен и помечается жёлтым), поэтому пакеты к каждому TAR используют именно выбранный keyset. Общее имя применяется ко всем импортируемым картам (пустое — берётся ICCID); режим импорта выбирает Дополнить (по умолчанию — существующие пресеты сохраняются, дубли ICCID пропускаются и перечисляются) или Заменить (хранилище сначала очищается). Предпросмотр перечисляет разобранные карты (ICCID, keysets, найденные коды) и каждую пропущенную строку/ключ с причиной — до того, как что-либо сохранено.
Импорт outfile загружает сразу много карт из outfile поставщика карт — текстового дампа инструмента персонализации: шапка с баннером и параметрами, затем разделённая пробелами строка колонок (среди токенов есть ICCID; первый токен может нести префикс вида var_out:) и по одной строке на карту. Всё до строки колонок и все неиспользуемые колонки игнорируются. Каждая строка данных должна содержать значение для каждой объявленной колонки — формат позиционный, поэтому пустое значение неотличимо от отсутствующего — а пара KICn/KIDn, объявленная в заголовке, должна иметь пригодное значение в каждой строке; нарушение делает весь файл некорректным (предпросмотр называет строку, импорт отклоняется). Разбираются ICCID (цифры, цифры с добивочным F до чётного числа нибблов, цифры с разделителями или сырой hex EF — всё приводится к одной форме), PIN1/PIN2/PUK1/PUK2, ADM (hex-значение ключа, 4–16 hex-цифр (чётное число) — например 3632333239463337), PSK (16 байт; необязательная колонка PSKID/PSK_ID задаёт её идентификатор, по умолчанию берётся ICCID карты) и нумерованные пары ключей KICn/KIDn — по одному keyset на пару, до 15. Байтов KIc/KID в файле нет: номер keyset — это номер колонки (KIC2 → keyset 2), а ниббл алгоритма определяется размером ключа — 8 байт DES, 24 байта 3DES3, а для 16 байт — выбором в предпросмотре: 3DES2 (по умолчанию) или AES; любой другой размер пропускает этот keyset с пометкой. TAR также не берутся из файла: предпросмотр показывает таблицу TAR, которую получат импортируемые карты (по умолчанию три ролевые записи с TAR по спецификации и MSL 16; их можно править, кнопка + TAR добавляет записи), и у каждой строки свой keyset — список из найденных в файле keysets (первый выбран заранее; при ненулевом MSL keyset обязателен и помечается жёлтым), поэтому пакеты к каждому TAR используют именно выбранный keyset. Начальное значение счётчика задаёт счётчик, с которого начинается каждый созданный keyset (по умолчанию 1 — значение хранилища; увеличьте его для карт, ушедших дальше). Общее имя применяется ко всем импортируемым картам (пустое — берётся ICCID); режим импорта выбирает Дополнить (по умолчанию — существующие пресеты сохраняются, дубли ICCID пропускаются и перечисляются) или Заменить (хранилище сначала очищается). Предпросмотр перечисляет разобранные карты (ICCID, keysets, найденные коды) и каждую пропущенную строку/ключ с причиной — до того, как что-либо сохранено.
The SCP81 column shows whether the preset supplies a usable PSK pair: ✓ (green) — identity and key set; ⚠ (amber) — only one of the two, so the listener ignores the preset; — — no PSK. PSK identity and key must be set together. Add preset opens the editor with a fresh preset; Edit loads the row's preset into it so fields can be changed without re-entering the card; Save stores it and returns to the list, Cancel discards the edits; Remove deletes the row (list only). Presets can be shared with Export to file and restored with Import from file. The selected card preset auto-fills the Secured Packet form and sets the TAR for the operation (RAM/GP → ISD TAR, SIM RFM → UICC RFM TAR, USIM RFM → ADF RFM TAR); a TAR typed into the Secured Packet form by hand is kept when sending - the counter, keys and the TAR's MSL are still re-read from the preset; the SPI1 is seeded from the TAR's MSL and a lower value warns (the server returns it as a warning too); edits are pushed into a running SCP81 listener automatically.
Import outfile imports many cards at once from a card vendor's outfile — the personalization tool's plain-text dump: a banner and a configuration header, then a whitespace-separated column line (the tokens include ICCID; the first token may carry a var_out:-style prefix) and one row per card. Everything before the column line and every unused column is ignored. Every data row must carry a value for every declared column — the format is positional, so an empty value is indistinguishable from a missing one — and a KICn/KIDn pair named in the header must have a usable value in every row; a violation makes the whole file invalid (the preview reports the line and the import is refused). The parser reads ICCID (digits, the digits with an odd-nibble F pad, spaced digits or the raw EF hex — all normalised to one form), PIN1/PIN2/PUK1/PUK2, ADM (the key's hex value, 4–16 hex digits in byte pairs — e.g. 3632333239463337), PSK (16 bytes; an optional PSKID/PSK_ID names its identity, defaulting to the card's ICCID) and the numbered key pairs KICn/KIDn — one keyset per pair, up to 15. The KIc/KID bytes are never in the file: the keyset number is the column number (KIC2 → keyset 2) and the algorithm nibble follows the key size — 8 bytes DES, 24 bytes 3DES3, and for 16 bytes the preview's choice, 3DES2 (default) or AES; any other size skips that keyset with a note. The TARs never come from the file either: the preview shows the TAR table the imported cards get (the three role entries with their spec TARs and MSL 16 by default, editable, with + TAR for extra entries) and every row carries its own keyset — a select over the keysets found in the file (the first one is preselected; a non-zero MSL needs one, marked amber), so each TAR's packets use exactly the keyset you choose. A common name is applied to every imported card (empty falls back to the ICCID); Import mode chooses Merge (default — existing presets are kept, duplicate ICCIDs are skipped and reported) or Replace (the store is wiped first). The preview lists the parsed cards (ICCID, keysets, the codes found) and every skipped row/key with its reason before anything is stored.
Import outfile imports many cards at once from a card vendor's outfile — the personalization tool's plain-text dump: a banner and a configuration header, then a whitespace-separated column line (the tokens include ICCID; the first token may carry a var_out:-style prefix) and one row per card. Everything before the column line and every unused column is ignored. Every data row must carry a value for every declared column — the format is positional, so an empty value is indistinguishable from a missing one — and a KICn/KIDn pair named in the header must have a usable value in every row; a violation makes the whole file invalid (the preview reports the line and the import is refused). The parser reads ICCID (digits, the digits with an odd-nibble F pad, spaced digits or the raw EF hex — all normalised to one form), PIN1/PIN2/PUK1/PUK2, ADM (the key's hex value, 4–16 hex digits in byte pairs — e.g. 3632333239463337), PSK (16 bytes; an optional PSKID/PSK_ID names its identity, defaulting to the card's ICCID) and the numbered key pairs KICn/KIDn — one keyset per pair, up to 15. The KIc/KID bytes are never in the file: the keyset number is the column number (KIC2 → keyset 2) and the algorithm nibble follows the key size — 8 bytes DES, 24 bytes 3DES3, and for 16 bytes the preview's choice, 3DES2 (default) or AES; any other size skips that keyset with a note. The TARs never come from the file either: the preview shows the TAR table the imported cards get (the three role entries with their spec TARs and MSL 16 by default, editable, with + TAR for extra entries) and every row carries its own keyset — a select over the keysets found in the file (the first one is preselected; a non-zero MSL needs one, marked amber), so each TAR's packets use exactly the keyset you choose. Start counter value sets the counter every created keyset starts from (default 1 — the store's value; raise it for cards already past it). A common name is applied to every imported card (empty falls back to the ICCID); Import mode chooses Merge (default — existing presets are kept, duplicate ICCIDs are skipped and reported) or Replace (the store is wiped first). The preview lists the parsed cards (ICCID, keysets, the codes found) and every skipped row/key with its reason before anything is stored.