diff --git a/docs/api.md b/docs/api.md index 62702a8..452e584 100644 --- a/docs/api.md +++ b/docs/api.md @@ -336,10 +336,14 @@ into a preview. - `tars` — the TAR table every imported card gets (defaults to the three role entries with their spec TARs and MSL 16). A malformed table (a non-3-byte TAR, a non-1-byte MSL, a duplicate) is refused with `400`. -- `tar_keyset` — one **global default keyset** (1–15) written into every TAR - entry of every imported card. Without it the card's first keyset is used - (a multi-keyset card would otherwise fail the store's "a non-zero MSL needs - a default keyset" rule). +- `tars` entries may carry their own `keyset` (1–15 — the preview's per-row + choice, v3.29.1): it wins; the entries without one fall back to + `tar_keyset`, and without that to the card's first keyset (a multi-keyset + card would otherwise fail the store's "a non-zero MSL needs a default + keyset" rule). A keyset outside 1–15 is refused with `400`. +- `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). 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 9f74fa9..53e602c 100644 --- a/frontend/help-ru.html +++ b/frontend/help-ru.html @@ -371,7 +371,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:) и по одной строке на карту. Всё до строки колонок и все неиспользуемые колонки игнорируются. Разбираются 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 по умолчанию, применяемый ко всем записям TAR — он обязателен для карты с несколькими keysets (ненулевой MSL должен называть keyset). Общее имя применяется ко всем импортируемым картам (пустое — берётся ICCID); режим импорта выбирает Дополнить (по умолчанию — существующие пресеты сохраняются, дубли ICCID пропускаются и перечисляются) или Заменить (хранилище сначала очищается). Предпросмотр перечисляет разобранные карты (ICCID, keysets, найденные коды) и каждую пропущенную строку/ключ с причиной — до того, как что-либо сохранено.

+

Импорт outfile загружает сразу много карт из outfile поставщика карт — текстового дампа инструмента персонализации: шапка с баннером и параметрами, затем разделённая пробелами строка колонок (среди токенов есть ICCID; первый токен может нести префикс вида var_out:) и по одной строке на карту. Всё до строки колонок и все неиспользуемые колонки игнорируются. Разбираются 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, найденные коды) и каждую пропущенную строку/ключ с причиной — до того, как что-либо сохранено.

diff --git a/frontend/help.html b/frontend/help.html index 985c97e..6ae8742 100644 --- a/frontend/help.html +++ b/frontend/help.html @@ -370,7 +370,7 @@

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. 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 one default keyset applied to every TAR entry — required for a card with several keysets (a non-zero MSL must name a keyset). 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. 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.

diff --git a/frontend/index.html b/frontend/index.html index a8da2e3..ed292bc 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -1928,7 +1928,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.29.0'; +const SIMPLE_VERSION = '3.29.1'; document.getElementById('app-version').textContent = 'v' + SIMPLE_VERSION; // ===== view history (the browser Back/Forward buttons) ===== @@ -14856,7 +14856,7 @@ function cardsImportFile(input) { // shows the preview plus the controls: the common name, the 16-byte key // algorithm, the TAR table and its one global default keyset - the final call // imports with a mode. -let _cardsOutfile = null; // {text, file, name, algorithm16, tarKeyset, mode, preview} +let _cardsOutfile = null; // {text, file, name, algorithm16, mode, preview} let _cardsOutfileTars = 0; // the free TAR rows of the panel function cardsOutfilePick() { @@ -14879,7 +14879,7 @@ async function cardsOutfileFile(input) { } _cardsOutfile = { text: text, file: String(file.name || ''), name: String(file.name || '').replace(/\.[^.]+$/, ''), - algorithm16: '3des2', tarKeyset: null, mode: 'merge', preview: null }; + algorithm16: '3des2', mode: 'merge', preview: null }; _cardsOutfileTars = 0; cardsOutfileRender(); await cardsOutfilePreview(); @@ -14905,8 +14905,6 @@ function cardsOutfileControls() { if (document.getElementById('cards-of-mode')) { o.mode = val('cards-of-mode') === 'replace' ? 'replace' : 'merge'; } - const ks = parseInt(val('cards-of-keyset'), 10); - if (Number.isInteger(ks) && ks > 0) o.tarKeyset = ks; } // The TAR table as the panel shows it: the three role rows (their defaults @@ -14917,17 +14915,21 @@ function cardsOutfileTarsFromDom() { const el = document.getElementById(id); return el ? String(el.value).trim() : ''; }; + const ks = i => { + const v = parseInt(get('cards-of-tar-' + i + '-keyset'), 10); + return Number.isInteger(v) && v > 0 ? v : null; + }; const out = CARDS_TAR_ROLES.map((role, i) => ({ role: role, tar: get('cards-of-tar-' + i + '-tar').replace(/\s/g, '').toUpperCase(), msl: get('cards-of-tar-' + i + '-msl').replace(/\s/g, '').toUpperCase(), - desc: '', + desc: '', keyset: ks(i), })); for (let i = 0; i < _cardsOutfileTars; i++) { const idx = CARDS_TAR_ROLES.length + i; out.push({ tar: get('cards-of-tar-' + idx + '-tar').replace(/\s/g, '').toUpperCase(), msl: get('cards-of-tar-' + idx + '-msl').replace(/\s/g, '').toUpperCase(), - desc: get('cards-of-tar-' + idx + '-desc') }); + desc: get('cards-of-tar-' + idx + '-desc'), keyset: ks(idx) }); } return out; } @@ -14942,7 +14944,7 @@ function cardsOutfileTarsFromForm() { const e = rows[i]; if (e.role) { out.push({ role: e.role, tar: e.tar || cardsRoleDefault(e.role), - msl: e.msl || CARDS_MSL_DEFAULT, desc: '' }); + msl: e.msl || CARDS_MSL_DEFAULT, desc: '', keyset: e.keyset || null }); } else if (e.tar || e.msl || e.desc) { out.push(e); } @@ -14953,9 +14955,24 @@ function cardsOutfileTarsFromForm() { function cardsOutfileTarRowHtml(e, i) { const cls = 'border border-gray-300 dark:border-slate-600 text-xs rounded px-1.5 py-0.5 dark:bg-slate-800 font-mono'; const role = CARDS_TAR_ROLES[i] || ''; + // The keyset this TAR's packets use: one select per row, like the preset + // editor (v3.29.1); it defaults to the first parsed keyset, and a non-zero + // MSL without one gets the amber marker. + const opts = cardsOutfileKeysetOptions(); + const sel = e.keyset ? Number(e.keyset) : (opts.length ? opts[0].v : null); + const msl = String(e.msl || '').toUpperCase(); let html = '
'; html += ''; html += ''; + html += ''; + if (!sel && msl && msl !== '00') { + html += '\u26a0'; + } if (role) { html += '' + esc(CARDS_TAR_ROLE_DESC[role] || role) + ''; } else { @@ -15006,15 +15023,19 @@ function cardsOutfileTarRender(rows) { } // The keyset numbers the parsed cards carry (the global default's options). -function cardsOutfileKeysets() { - const out = []; +// The parsed keysets as the TAR rows' options: the union across the parsed +// cards, with their KIc/KID bytes for the labels (v3.29.1). +function cardsOutfileKeysetOptions() { + const seen = {}; (((_cardsOutfile || {}).preview || {}).presets || []).forEach(c => { (c.keysets || []).forEach(ks => { const v = spKeysetKvnOf(ks.kic); - if (v !== null && !out.includes(v)) out.push(v); + if (v !== null && !seen[v]) { + seen[v] = { v: v, kic: ks.kic || '??', kid: ks.kid || '??' }; + } }); }); - return out.sort((a, b) => a - b); + return Object.keys(seen).map(k => seen[k]).sort((a, b) => a.v - b.v); } function cardsOutfileResultHtml() { @@ -15059,15 +15080,6 @@ function cardsOutfileRender() { const panel = document.getElementById('cards-outfile-panel'); const o = _cardsOutfile; if (!panel || !o) return; - const keysets = cardsOutfileKeysets(); - // An empty or failed preview must not drop a chosen keyset: the value is - // only re-selected against a list that has keysets, and the option list is - // the preview's keysets plus a remembered value (so it stays visible). - if (keysets.length && !keysets.includes(o.tarKeyset)) o.tarKeyset = keysets[0]; - const options = keysets.slice(); - if (o.tarKeyset && !options.includes(o.tarKeyset)) options.push(o.tarKeyset); - options.sort((a, b) => a - b); - const selected = o.tarKeyset; let html = '
'; html += '' + esc(t('outfile import')) + ': ' + esc(o.file || '') + ''; @@ -15080,11 +15092,6 @@ function cardsOutfileRender() { ''; - html += ''; html += '