v3.20.0: the server-owned SCP80 counter (an untouched field = the preset's next value)

The counter an operation consumed was re-entered by the PWA on every send
(the form field was filled from the preset and posted back), so a stale tab
could send a value the card rejects (cntr_low), and typing in the field
silently wrote the preset.  Now the store is the single source of truth and
the form field is a per-send override (Option B).

- _preset_counter_seed: an explicit `cntr` in the request wins (a hand send,
  the counter probe or a pre-built packet may deliberately pick one);
  otherwise the preset store's value for the packet's keyset.  Wired into
  /api/send-ota (the APDU path; the pre-built `sp` path keeps the caller's
  bookkeeping value - the packet carries its own counter), /api/ram-install,
  /api/ram-install-app, /api/cap-compat, /api/tar-probe and /api/sp-verify
  (the reference must use the counter the JS packet was built with).
- the send-ota response echoes the effective `cntr` (a caller that omitted
  one learns what was used) and the OTA SEND log line prints it.
- persistence is unchanged and monotonic (presets.set_counter refuses
  backwards writes), pinned by tests: an explicit lower counter is used for
  the packet but never lowers the store, a higher accepted one is saved.
- PWA: the Secured packet counter field starts empty with the preset's next
  value as its placeholder (auto: <cntr>); typing affects that send only and
  is never written to the preset (spCntrSyncPreset is gone), spParams /
  getRamSpParams omit an empty counter, the RAM/send flows sync only the
  local preset copy (forward-only) instead of filling the field, the +/-
  buttons start from the effective value, and the preview/verify packet is
  built from the effective counter (genSp).  Placeholder translated EN/RU.
- the runner and /api/counter-probe keep their existing seeding (the probe
  already starts at the failed value and walks above it).
- docs: api.md's optional-`cntr` contract + seeding notes on every endpoint,
  help EN/RU 3.1.  Tests: 822 frontend + 734 Python; sw cache simple-v393.
This commit is contained in:
2026-10-05 22:22:50 +03:00
parent 0e06b918a7
commit 85cc4b9535
14 changed files with 331 additions and 101 deletions
File diff suppressed because one or more lines are too long
+2 -2
View File
@@ -281,7 +281,7 @@
<p class="mb-3">The <strong>SCP80</strong> top-level tab groups the SCP80-related views. It is switched by three pills: <strong>Secured Packet</strong>, <strong>RAM</strong> and <strong>TAR probe</strong>. Assembles SCP80 secured packets per ETSI TS 102 225. When a card is equipped the server reads its <strong>EF.ICCID</strong> (2FE2); if a card preset carries the same number (digits, or the raw EF hex), it is selected automatically in all three SCP80 views.</p>
<h3 id="secured-packet" class="text-lg font-medium mb-2">3.1 Secured Packet</h3>
<p class="mb-2">Builds SCP80 secured packets per ETSI TS 102 225. The <strong>Keyset</strong> selector next to the card preset selector picks which keyset of the preset supplies the keys and the counter; the send is refused when the preset does not define that keyset number or when its KIc/KID carry different numbers (TS 102 225 A.2). It is disabled until a card preset is selected. The start button stays disabled until a card preset and one of its keysets are selected. The packet's TAR field suggests the preset's TAR entries (each with its description and MSL); applying a preset sets the operation's TAR and seeds the SPI1 from that TAR's <strong>MSL</strong> (Minimum SPI1, TS 102 226 &sect;8.2.1.3.2.4 &mdash; the card checks it before the security processing and answers <code class="font-mono text-sm">0A</code> when the packet's SPI1 is below it). A value below the MSL shows an amber warning under the form; a hand-typed TAR keeps the operator's SPI1.</p>
<p class="mb-2">Builds SCP80 secured packets per ETSI TS 102 225. The <strong>Keyset</strong> selector next to the card preset selector picks which keyset of the preset supplies the keys and the counter; the send is refused when the preset does not define that keyset number or when its KIc/KID carry different numbers (TS 102 225 A.2). It is disabled until a card preset is selected. The start button stays disabled until a card preset and one of its keysets are selected. The packet's TAR field suggests the preset's TAR entries (each with its description and MSL); applying a preset sets the operation's TAR and seeds the SPI1 from that TAR's <strong>MSL</strong> (Minimum SPI1, TS 102 226 &sect;8.2.1.3.2.4 &mdash; the card checks it before the security processing and answers <code class="font-mono text-sm">0A</code> when the packet's SPI1 is below it). A value below the MSL shows an amber warning under the form; a hand-typed TAR keeps the operator's SPI1. The <strong>Counter</strong> field is an override: it starts empty and shows the preset's next counter as its placeholder &mdash; an empty field lets the server seed the packet from the stored counter and persist the value the card accepted; a typed value is used for that send only, is never written to the preset, and a lower one never rewinds the stored counter (only forward moves are persisted).</p>
<h4 id="packet-structure" class="font-medium mb-1">Packet structure</h4>
<table class="w-full text-sm mb-3 border-collapse">
<thead><tr class="border-b border-gray-300 dark:border-slate-700"><th class="text-left py-1 px-2">Field</th><th class="text-left py-1 px-2">Size</th><th class="text-left py-1 px-2">Description</th></tr></thead>
@@ -310,7 +310,7 @@
<li>AES requires a replay-protected counter: SPI1 bits b5&nbsp;b4 must be <code class="font-mono text-sm">10</code> (counter higher) or <code class="font-mono text-sm">11</code> (counter +1) per TS 102 225 &sect;5.1.2/&sect;5.1.3.1</li>
<li>Padding byte configurable (<code class="font-mono text-sm">00</code> default, or <code class="font-mono text-sm">FF</code>)</li>
</ul>
<p class="text-sm mb-3">A &ldquo;Verify vs pySim&rdquo; button cross-checks the assembled packet against pySim&rsquo;s reference <code class="font-mono text-sm">OtaDialectSms.encode_cmd</code>. A &ldquo;Send to Card&rdquo; button delivers it via SMS-PP-DOWNLOAD ENVELOPE (when connected to the server). The 2-byte CPL prefix is transmitted whenever the packet is ciphered or carries RC/CC/DS (it is part of their input) and whenever the packet is concatenated; a single unprotected SMS keeps pySim&rsquo;s CHL-first form (TS 31.115 Table 1 NOTE). Under the packet field the app reports its size and how many SMS it takes; a packet that does not fit one SMS is sent as a <strong>concatenated</strong> download (TS 31.115 &sect;4.3) &mdash; the packet is split into SMS user-data parts (first SM 132 octets, following ones 134; the first one additionally carries the concatenation and CPI information elements) and the segments are sent in order. More than 5 segments is refused, that being the practical limit of the card&rsquo;s concatenation buffer. The returned Proof of Receipt is decoded and shown as a PoR status line (status, TAR, counter, raw PoR); the last command&rsquo;s status word and response data are filled into the <strong>R-APDU parser</strong> panel, and a successful PoR advances the replay counter (when SPI1 carries a counter check &mdash; b5 b4 &ne; 00; without one no counter is advanced or saved) and clears the packet. A <strong>low-counter</strong> verdict (<code class="font-mono text-sm">cntr_low</code>, or a warning ENVELOPE answer that still carries such a PoR) is <em>not</em> recoverable by retrying: every SCP80/RAM operation stops immediately. The card never reports its counter (the PoR&rsquo;s CNTR field is a copy of the packet&rsquo;s), so the notice offers a bounded <strong>Sync counter</strong> probe &mdash; a read-only command with increasing counter values (doubling steps, a 32-bit ceiling, at most 40 packets) until the card accepts one, then accepted+1 is stored (a search stopped by a security verdict after a counter rejection saves the value too, with an amber warning to check the security settings) &mdash; and a <strong>Go to preset</strong> button for raising the counter by hand; nothing else is written automatically.</p>
<p class="text-sm mb-3">A &ldquo;Verify vs pySim&rdquo; button cross-checks the assembled packet against pySim&rsquo;s reference <code class="font-mono text-sm">OtaDialectSms.encode_cmd</code>. A &ldquo;Send to Card&rdquo; button delivers it via SMS-PP-DOWNLOAD ENVELOPE (when connected to the server). The 2-byte CPL prefix is transmitted whenever the packet is ciphered or carries RC/CC/DS (it is part of their input) and whenever the packet is concatenated; a single unprotected SMS keeps pySim&rsquo;s CHL-first form (TS 31.115 Table 1 NOTE). Under the packet field the app reports its size and how many SMS it takes; a packet that does not fit one SMS is sent as a <strong>concatenated</strong> download (TS 31.115 &sect;4.3) &mdash; the packet is split into SMS user-data parts (first SM 132 octets, following ones 134; the first one additionally carries the concatenation and CPI information elements) and the segments are sent in order. More than 5 segments is refused, that being the practical limit of the card&rsquo;s concatenation buffer. The returned Proof of Receipt is decoded and shown as a PoR status line (status, TAR, counter, raw PoR); the last command&rsquo;s status word and response data are filled into the <strong>R-APDU parser</strong> panel, and a successful PoR advances the replay counter (when SPI1 carries a counter check &mdash; b5 b4 &ne; 00; without one no counter is advanced or saved) and clears the packet &mdash; the server persists the accepted counter into the preset, the form&rsquo;s counter field stays empty (its placeholder follows the stored value) unless the operator typed an override. A <strong>low-counter</strong> verdict (<code class="font-mono text-sm">cntr_low</code>, or a warning ENVELOPE answer that still carries such a PoR) is <em>not</em> recoverable by retrying: every SCP80/RAM operation stops immediately. The card never reports its counter (the PoR&rsquo;s CNTR field is a copy of the packet&rsquo;s), so the notice offers a bounded <strong>Sync counter</strong> probe &mdash; a read-only command with increasing counter values (doubling steps, a 32-bit ceiling, at most 40 packets) until the card accepts one, then accepted+1 is stored (a search stopped by a security verdict after a counter rejection saves the value too, with an amber warning to check the security settings) &mdash; and a <strong>Go to preset</strong> button for raising the counter by hand; nothing else is written automatically.</p>
<h3 id="ram" class="text-lg font-medium mb-2">3.2 RAM</h3>
<p class="mb-2">Delivers Remote Application Management operations as SCP80 secured packets via SMS-PP-DOWNLOAD ENVELOPE. The card must support SCP03 (AES or 3DES). A saved card preset from the <strong>Cards</strong> tab provides the keys, the TAR table and the counter (RAM uses the preset's <strong>ISD TAR</strong>, <code class="font-mono text-sm">000000</code> by default; the SPI1 is derived from that TAR's MSL). The <strong>Keyset</strong> selector next to the preset selector picks the keyset whose keys and counter the operation uses. It is disabled until a card preset is selected. The start button stays disabled until a card preset and one of its keysets are selected. The <strong>Format</strong> selector pins the remote command format: <strong>Auto (detect)</strong> probes the read-only GET STATUS command compact and in both expanded codings and keeps the first that the card executes, <strong>Compact</strong> sends the bare C-APDU, and <strong>Expanded (AA, definite length)</strong> / <strong>Expanded (AE 80, indefinite length)</strong> wrap it in the TS 102 226 &sect;5.2.1 scripting template (both execute on the live ISD; a template whose declared lengths do not match its body draws a Bad format TLV, which the operation shows as the step failure). The listing and registry queries follow that format: compact listings keep the chained GET RESPONSE, while an expanded run sends the same P2=00 queries wrapped and unchained (the reference TCA loader&rsquo;s form, Le=&rsquo;00&rsquo; returns the listing directly), and a registry query the card refuses in the current format is retried in the other formats &mdash; the report names the one that served it. A <strong>next-occurrence page</strong> (<code class="font-mono text-sm">P2=03</code>) that a format refuses is retried in the other formats too &mdash; the expanded codings first (the serving one first when it is expanded), the compact command string last, because a compact page attempt can consume the page without delivering it (the card answers <code class="font-mono text-sm">61xx</code> and the chained GET RESPONSE fails; every later format then sees the occurrence already gone) &mdash; some cards serve the expanded next page only wrapped in the <code class="font-mono text-sm">AA</code> template &mdash; and a listing is marked <code class="font-mono text-sm">(first page only)</code> only when the card promised more (<code class="font-mono text-sm">6310</code>) and no format could fetch the follow-up; in <strong>Auto</strong> the explorer also queries entries the bulk listing left without details individually by AID (a few extra packets). The card-resources block also names the card&rsquo;s inferred <strong>ETSI release</strong> (<code class="font-mono text-sm">uicc.toolkit</code> version &rarr; REL-N, the same mapping as the CAP analysis; shown only when the expanded registry returned the versions). A package whose own listing carries no version derives it from its applet instance when one exists &mdash; the package&rsquo;s module AIDs are the applet instance AIDs, and the row is annotated as coming from the app instance &mdash; so a card that refuses every tag-list form still shows package versions wherever an applet instance exists.</p>
+103 -55
View File
@@ -658,7 +658,7 @@
<label class="block mb-1 text-sm font-medium text-gray-700 dark:text-slate-300">Counter (5 bytes)</label>
<div class="flex gap-1 items-center">
<button type="button" onclick="spCntrAdjust(-1)" class="px-2.5 py-2 border border-gray-300 dark:border-slate-600 text-sm rounded hover:bg-gray-200 dark:bg-slate-700 dark:hover:bg-slate-600">−</button>
<input id="sp-cntr" oninput="spInvalidate()" onchange="spCntrSyncPreset()" class="font-mono border border-gray-300 dark:border-slate-600 text-sm rounded px-3 py-1.5 flex-1 dark:bg-slate-800" placeholder="0000000001" maxlength="10" value="0000000001">
<input id="sp-cntr" oninput="spInvalidate()" class="font-mono border border-gray-300 dark:border-slate-600 text-sm rounded px-3 py-1.5 flex-1 dark:bg-slate-800" placeholder="auto" maxlength="10">
<button type="button" onclick="spCntrAdjust(1)" class="px-2.5 py-2 border border-gray-300 dark:border-slate-600 text-sm rounded hover:bg-gray-200 dark:bg-slate-700 dark:hover:bg-slate-600">+</button>
</div>
</div>
@@ -1877,7 +1877,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.19.2';
const SIMPLE_VERSION = '3.20.0';
document.getElementById('app-version').textContent = 'v' + SIMPLE_VERSION;
// ===== Tab switching =====
@@ -4822,7 +4822,9 @@ function packToSp(sourceId) {
}
function spCntrAdjust(delta) {
const el = document.getElementById('sp-cntr');
let val = parseInt(el.value.replace(/[^0-9a-fA-F]/g, ''), 16) || 0;
// The ± buttons start from the effective counter (typed override, else the
// preset's next value) and turn it into an explicit override.
let val = parseInt(spCntrEffective(), 16) || 0;
val = Math.max(0, val + delta) % 0x10000000000; // wrap the 5-byte counter
el.value = val.toString(16).padStart(10, '0').toUpperCase();
}
@@ -5099,6 +5101,9 @@ function spShowSizeInfo() {
}
function _genSpBuild() {
// The counter the packet carries: the typed override, else the preset's
// next value (the server seeds the same way when the counter is omitted).
const cntrHex = spCntrEffective();
const apduHex = (document.getElementById('sp-apdu').value || '').replace(/[^0-9a-fA-F]/g, '');
if (!apduHex) { document.getElementById('sp-result').value = 'Error: specify APDU'; return; }
@@ -5107,7 +5112,6 @@ function _genSpBuild() {
const kicHex = document.getElementById('sp-kic-hex').value;
const kidHex = document.getElementById('sp-kid-hex').value;
const tarHex = (document.getElementById('sp-tar').value || '').replace(/[^0-9a-fA-F]/g, '').toUpperCase().padEnd(6, '0').slice(0, 6);
const cntrHex = (document.getElementById('sp-cntr').value || '').replace(/[^0-9a-fA-F]/g, '').padStart(10, '0').slice(0, 10);
const kicKeyHex = (document.getElementById('sp-kic-key').value || '').replace(/[^0-9a-fA-F]/g, '');
const kidKeyHex = (document.getElementById('sp-kid-key').value || '').replace(/[^0-9a-fA-F]/g, '');
const padByte = parseInt(document.getElementById('sp-padding').value, 16);
@@ -8569,42 +8573,58 @@ function spPresetIdx() {
return (!isNaN(idx) && cards[idx]) ? idx : -1;
}
// The SCP80 form's counter input: a deliberate human edit, written to the
// server-side preset (v3.8.0). The counter an *operation* accepted is
// persisted by the server itself - the send/RAM flows only sync the local copy
// through spCntrLocalSync().
function spCntrSyncPreset() {
// The SCP80 form's counter input is a per-send override (v3.20.0): an empty
// field means "let the server seed the counter from the preset store" - the
// store is the source of truth and advances monotonically on accepted
// packets; typing a value overrides it for that send only and is never
// written to the preset. The preset's next value shows as the placeholder.
function spPresetCounterValue() {
const idx = spPresetIdx();
if (idx < 0) return false;
const preset = cards[idx];
const value = (document.getElementById('sp-cntr').value || '').trim().toUpperCase();
if (idx < 0) return '';
const kvn = spKeysetKvnOf((document.getElementById('sp-kic-hex') || {}).value) ||
spKeysetKvnOf((document.getElementById('sp-kid-hex') || {}).value) || 0;
const ks = spKeysetFor(preset, kvn);
if (ks) ks.cntr = value;
cardsRender();
if (preset.id && ks) {
pysimFetch('/api/presets/update', { id: preset.id, fields: { keysets: spKeysetList(preset) } })
.then(res => {
if (res && res.error) throw new Error(res.error);
// the store normalises the counter (fixed 10-hex form)
if (res && res.preset) { cards[idx] = res.preset; cardsRender(); spKeysetSync(); }
})
.catch(e => ioStatus('cards-io', t('Counter not saved:') + ' ' + e.message));
}
return true;
// the same fallback cardsApplyFields uses: the matching keyset, else the
// preset's first one (an undefined duplicate would otherwise leave the
// placeholder empty)
const ks = (kvn && spKeysetFor(cards[idx], kvn)) || spKeysetList(cards[idx])[0] || null;
return (ks && ks.cntr) || '';
}
// Keep the selected preset in step with a counter the server already persisted
// (the operations report it as final_cntr): display only, no write.
function spCntrPlaceholder() {
const el = document.getElementById('sp-cntr');
if (!el) return;
const v = spPresetCounterValue();
el.placeholder = v ? t('auto') + ': ' + v : t('auto');
}
// The counter the packet is built with (preview / verify): the typed
// override, else the preset's next value, else the historic 1 default.
function spCntrEffective() {
const el = document.getElementById('sp-cntr');
const typed = ((el && el.value) || '').replace(/[^0-9a-fA-F]/g, '');
const v = typed || spPresetCounterValue() || '1';
return v.toUpperCase().padStart(10, '0').slice(0, 10);
}
// Numeric "b is ahead of a" for two hex counters (the store is monotonic).
function spCntrAhead(a, b) {
try { return parseInt(String(b), 16) > parseInt(String(a), 16); }
catch (e) { return false; }
}
// Keep the selected preset's copy in step with a counter the server already
// persisted (the operations report it as final_cntr): display only, no write,
// and the copy only moves forward (the store is monotonic).
function spCntrLocalSync(value) {
const idx = spPresetIdx();
if (idx < 0) return;
const kvn = spKeysetKvnOf((document.getElementById('sp-kic-hex') || {}).value) ||
spKeysetKvnOf((document.getElementById('sp-kid-hex') || {}).value) || 0;
const ks = spKeysetFor(cards[idx], kvn);
if (ks) ks.cntr = value;
const v = String(value || '').toUpperCase();
if (ks && v && (!ks.cntr || spCntrAhead(ks.cntr, v))) ks.cntr = v;
cardsRender();
spCntrPlaceholder();
}
function spParams() {
@@ -8616,11 +8636,14 @@ function spParams() {
kic: document.getElementById('sp-kic-hex').value,
kid: document.getElementById('sp-kid-hex').value,
tar: (document.getElementById('sp-tar').value || '').replace(/[^0-9a-fA-F]/g, '').toUpperCase().padEnd(6, '0').slice(0, 6),
cntr: document.getElementById('sp-cntr').value,
kicKey: document.getElementById('sp-kic-key').value,
kidKey: document.getElementById('sp-kid-key').value,
apdu: document.getElementById('sp-apdu').value,
};
// The counter is sent only when the field carries an explicit override;
// empty = the server seeds it from the preset store (v3.20.0).
const cntr = (document.getElementById('sp-cntr').value || '').replace(/[^0-9a-fA-F]/g, '');
if (cntr) p.cntr = cntr;
if (_spRamFormat) p.ram_format = _spRamFormat;
return p;
}
@@ -8714,18 +8737,19 @@ async function pysimSendOta() {
// untouched - the card did not consume the packet (v3.6.3; the old
// "advance always" rule silently reverted preset edits).
if (spPorAccepted(por)) {
const cntrEl = document.getElementById('sp-cntr');
const spi1Now = (document.getElementById('sp-spi1') || {}).value;
let next = '';
if (data.final_cntr) {
// the server persisted the accepted counter; sync the display
cntrEl.value = data.final_cntr;
msg += ' | CNTR -> ' + cntrEl.value;
spCntrLocalSync(cntrEl.value);
// the server persisted the accepted counter; sync the local
// copy (display only - the form field is an override)
next = String(data.final_cntr);
} else if (spCounterTracked(spi1Now)) {
// an older server: advance the local working copy
cntrEl.value = spNextCntr(cntrEl.value);
msg += ' | CNTR -> ' + cntrEl.value;
spCntrLocalSync(cntrEl.value);
next = spNextCntr(spCntrEffective());
}
if (next) {
msg += ' | CNTR -> ' + next;
spCntrLocalSync(next);
} else {
// SPI1 without a counter check: the card keeps no replay
// value, so nothing is advanced (keyless SPI1 00 packets)
@@ -9217,18 +9241,22 @@ function getRamSpParams(selId) {
const sel = document.getElementById(selId || 'ram-card-sel');
const idx = sel ? parseInt(sel.value, 10) : NaN;
const preset = (!isNaN(idx) && cards[idx]) ? cards[idx] : null;
return {
const p = {
preset_id: (preset && preset.id) || '',
spi1: document.getElementById('sp-spi1').value,
spi2: document.getElementById('sp-spi2-hex').value,
kic: document.getElementById('sp-kic-hex').value,
kid: document.getElementById('sp-kid-hex').value,
tar: (document.getElementById('sp-tar').value || '').replace(/[^0-9a-fA-F]/g, '').toUpperCase().padEnd(6, '0').slice(0, 6),
cntr: (document.getElementById('sp-cntr').value || '0000000001').replace(/[^0-9a-fA-F]/g, ''),
kicKey: (document.getElementById('sp-kic-key').value || '').replace(/[^0-9a-fA-F]/g, ''),
kidKey: (document.getElementById('sp-kid-key').value || '').replace(/[^0-9a-fA-F]/g, ''),
ram_format: (document.getElementById('ram-format') || {}).value || 'auto',
};
// Override only when typed; empty = the server seeds the counter from the
// preset store (v3.20.0).
const cntr = (document.getElementById('sp-cntr').value || '').replace(/[^0-9a-fA-F]/g, '');
if (cntr) p.cntr = cntr;
return p;
}
function ramIncrementCntr(cntr) {
@@ -9238,18 +9266,20 @@ function ramIncrementCntr(cntr) {
function ramSaveCntr(cntr) {
// Keep the local copy in step with the counter the server persisted for the
// operation (v3.8.0): display only - the store already holds it.
const el = document.getElementById('sp-cntr');
if (el) el.value = cntr;
// operation (v3.8.0): display only - the store already holds it, and the
// copy only moves forward (the store is monotonic). The form's counter
// field stays an explicit override; empty = the server seeds it.
const selIdx = parseInt((document.getElementById('ram-card-sel') || {}).value, 10);
if (!isNaN(selIdx) && cards[selIdx]) {
const kvn = spKeysetKvnOf((document.getElementById('sp-kic-hex') || {}).value) ||
spKeysetKvnOf((document.getElementById('sp-kid-hex') || {}).value) || 0;
const ks = spKeysetFor(cards[selIdx], kvn);
if (ks) ks.cntr = cntr;
const v = String(cntr || '').toUpperCase();
if (ks && v && (!ks.cntr || spCntrAhead(ks.cntr, v))) ks.cntr = v;
cardsRender();
ramRender();
}
spCntrPlaceholder();
}
// Send a single GP APDU wrapped in SCP80 via /api/send-ota
@@ -11609,8 +11639,8 @@ async function ramSyncCounter(presetIdx, view) {
await cardsFetch();
// the keyset selects' labels carry the counter - refresh them too
spKeysetSync();
const cntrEl = document.getElementById('sp-cntr');
if (cntrEl && data.stored_cntr) cntrEl.value = data.stored_cntr;
// the field stays an override; its placeholder shows the stored value
spCntrPlaceholder();
}
if (data.success) {
const msg = t('Counter synced') + ': ' + esc(data.accepted_cntr) + ' \u2192 ' +
@@ -12498,7 +12528,10 @@ function spKeysetApply(ks) {
updateSpKid();
set('sp-kic-key', ks.kicKey || '');
set('sp-kid-key', ks.kidKey || '');
set('sp-cntr', ks.cntr || '');
// The counter field is an override: a keyset switch clears it (empty =
// the server seeds the packet counter, v3.20.0).
set('sp-cntr', '');
spCntrPlaceholder();
spInvalidate();
updateSp();
}
@@ -12950,7 +12983,7 @@ function cardsAutoSelectByIccid(iccid) {
// packet TAR alone: the plain SCP80 send re-reads only the preset-owned
// counter/keys/SPI, a manually entered target TAR (push/link triggers,
// applet OTA) must survive.
function cardsApplyFields(idx, keepTar) {
function cardsApplyFields(idx, keepTar, keepCntr) {
const c = cards[parseInt(idx)];
if (!c) return false;
// The TAR of the current operation (ISD for RAM/GP, the RFM TAR for the RFM
@@ -12986,10 +13019,18 @@ function cardsApplyFields(idx, keepTar) {
document.getElementById('sp-kid-idx').value = ((kidByte >> 4) & 0x0F).toString(16).toUpperCase();
document.getElementById('sp-kid-alg').value = (kidByte & 0x0F).toString(16).padStart(2, '0');
updateSpKid();
document.getElementById('sp-cntr').value = ks.cntr || '';
document.getElementById('sp-kic-key').value = ks.kicKey || '';
document.getElementById('sp-kid-key').value = ks.kidKey || '';
}
// The counter field is an override: applying a preset clears it (empty =
// auto, the server seeds from the store); the pre-send refresh keeps a
// typed override (`keepCntr`). The placeholder always shows the preset's
// next value.
if (!keepCntr) {
const cntrEl = document.getElementById('sp-cntr');
if (cntrEl) cntrEl.value = '';
}
spCntrPlaceholder();
if (!keepTar) document.getElementById('sp-tar').value = cardsRoleTar(c, _spTarKey);
spTarListRender(c);
spInvalidate();
@@ -13000,8 +13041,8 @@ function cardsApplyFields(idx, keepTar) {
return true;
}
function cardsApply(idx, keepTar) {
if (!cardsApplyFields(idx, keepTar)) {
function cardsApply(idx, keepTar, keepCntr) {
if (!cardsApplyFields(idx, keepTar, keepCntr)) {
// "— Select card —": there is no keyset to choose, and the preset
// warning must not outlive the selection it described.
spKeysetSync();
@@ -13014,16 +13055,18 @@ function cardsApply(idx, keepTar) {
}
// SCP80/RAM operations re-read the selected preset before starting: the
// Cards tab (or a counter write-back) may have changed it after the form was
// filled, and a stale counter is rejected by the card (cntr_low) and would
// then be written back over the preset. Returns the preset counter ('' when
// no preset is selected).
// Cards tab (or another window) may have changed the keys, SPI or the
// counter the server will seed. A typed counter override survives the
// refresh - it is the user's explicit choice for the send. Returns the
// preset's counter ('' when no preset is selected).
function spRefreshFromPreset(selId, keepTar) {
const sel = document.getElementById(selId || 'sp-card-sel');
const idx = sel ? parseInt(sel.value, 10) : NaN;
if (isNaN(idx) || !cards[idx]) return '';
if (selId === 'ram-card-sel') _spTarKey = 'isd';
cardsApply(idx, keepTar);
// keepCntr: the form field is an override; do not re-fill it from the
// preset (empty = the server seeds the packet counter, v3.20.0).
cardsApply(idx, keepTar, true);
return cards[idx].cntr;
}
@@ -21244,6 +21287,7 @@ const LANG_RU = {
'Test script running': 'Выполняется тест-скрипт',
'Preset': 'Пресет',
'Counter': 'Счётчик',
'auto': 'авто',
'Counter (hex)': 'Счётчик (hex)',
'No run yet.': 'Запусков пока нет.',
'running': 'выполняется',
@@ -21774,6 +21818,8 @@ function refreshDynamicI18n() {
if (isViewVisible('profiler-scan-modal')) profilerScanRefreshOptions();
pysimUpdateCardActionLabels();
pysimUpdateStateIndicator();
// the counter field's placeholder carries a t() string (auto / авто)
spCntrPlaceholder();
if (isViewVisible('tab-cards')) {
cardsRender();
cardsSetFormMode();
@@ -21841,6 +21887,8 @@ chainInit('chain-ram');
ramResetGrants();
updateInstallParamsHex();
translatePage();
// the counter field's placeholder carries a t() string (auto / авто)
spCntrPlaceholder();
// PWA
let deferredPrompt;
const installBtn = document.getElementById('install-btn');
+1 -1
View File
@@ -1,4 +1,4 @@
const CACHE = 'simple-v392';
const CACHE = 'simple-v393';
const URLS = [
'index.html',
'help.html',
+30 -9
View File
@@ -31,6 +31,8 @@ let code = '';
for (const fn of ['cardsTarList', 'cardsRoleDefault', 'cardsRoleTar',
'cardsTarEntry', 'cardsTarMsl', 'cardsApplyFields', 'cardsApply',
'spRefreshFromPreset', 'spPorAccepted', 'spNextCntr', 'spPresetIdx',
'spPresetCounterValue', 'spCntrPlaceholder', 'spCntrEffective', 'spCntrAhead',
'spCntrAdjust',
'spKeysetKvnOf', 'spKeysetList', 'spKeysetFor', 'spKeysetCheck',
'spKeysetOptionsHtml', 'cardsKeysetRowHtml', 'cardsKeysetRowsRender',
'cardsKeysetAdd', 'cardsKeysetRemove', 'cardsKeysetKvnUpdate',
@@ -51,6 +53,7 @@ eval(code);
globalThis._genSpBuild = () => {};
globalThis.spShowSizeInfo = () => {};
globalThis.spKeysetSync = globalThis.spKeysetSync || (() => {});
globalThis.t = s => s;
// The SP form is a working copy: the preset is the source of truth, and
// every SCP80/RAM operation re-reads it before starting (v3.6.3). The plain
@@ -81,16 +84,23 @@ function fakeEnv(selValue, selId, presetCntr) {
return { els, gen: () => gen };
}
test('spRefreshFromPreset re-reads the edited preset before an operation', () => {
test('spRefreshFromPreset keeps an explicit counter override, empty = auto', () => {
const env = fakeEnv('0', 'sp-card-sel', '00000000AA');
env.els['sp-cntr'].value = '0000000001'; // stale form copy
env.els['sp-cntr'].value = '0000000001'; // explicit override
assert.strictEqual(spRefreshFromPreset('sp-card-sel'), '00000000AA');
assert.strictEqual(env.els['sp-cntr'].value, '00000000AA');
assert.ok(env.gen() > 0, 'the packet must be regenerated from the new counter');
assert.strictEqual(env.els['sp-cntr'].value, '0000000001',
'a typed counter survives the pre-send refresh');
assert.ok(env.gen() > 0, 'the packet must be regenerated from the preset');
// an empty field means "auto": the server seeds the counter, and the
// preset's next value is shown as the placeholder (v3.20.0)
env.els['sp-cntr'].value = '';
spRefreshFromPreset('sp-card-sel');
assert.strictEqual(env.els['sp-cntr'].value, '');
assert.match(env.els['sp-cntr'].placeholder, /00000000AA/);
// no preset selected: the manual form is left alone
globalThis.cards = [];
assert.strictEqual(spRefreshFromPreset('sp-card-sel'), '');
assert.strictEqual(env.els['sp-cntr'].value, '00000000AA');
assert.strictEqual(env.els['sp-cntr'].value, '');
});
test('spRefreshFromPreset for the RAM selector targets the ISD TAR', () => {
@@ -105,23 +115,34 @@ test('the pre-send refresh keeps a hand-edited packet TAR (v3.6.21)', () => {
env.els['sp-tar'].value = 'AF4D01'; // e.g. a push/link trigger target
assert.strictEqual(spRefreshFromPreset('sp-card-sel', true), '0000000020');
assert.strictEqual(env.els['sp-tar'].value, 'AF4D01', 'the typed TAR must survive the send');
assert.strictEqual(env.els['sp-cntr'].value, '0000000020', 'the counter still refreshes');
assert.strictEqual(env.els['sp-cntr'].value, '', 'the counter field stays an override');
assert.match(env.els['sp-cntr'].placeholder, /0000000020/);
// an explicit preset apply (or a pack) still sets the TAR
cardsApplyFields(0);
assert.strictEqual(env.els['sp-tar'].value, 'B00000');
});
test('cardsApplyFields fills the form without generating a packet', () => {
test('cardsApplyFields leaves the counter to the server (auto) and shows it as a placeholder', () => {
const env = fakeEnv('0', 'sp-card-sel', '0000000007');
env.els['sp-cntr'].value = 'nonsense';
env.els['sp-cntr'].value = 'nonsense'; // an old override
assert.strictEqual(cardsApplyFields(0), true);
assert.strictEqual(env.els['sp-cntr'].value, '0000000007');
assert.strictEqual(env.els['sp-cntr'].value, '',
'applying a preset clears the override (empty = the server seeds it)');
assert.match(env.els['sp-cntr'].placeholder, /0000000007/);
assert.strictEqual(env.gen(), 0, 'a plain field refresh must not rebuild the packet');
cardsApply(0);
assert.strictEqual(env.gen(), 1);
assert.strictEqual(cardsApplyFields(3), false);
});
test('the counter +/- buttons start from the preset value and create an override', () => {
const env = fakeEnv('0', 'sp-card-sel', '0000000020');
spCntrAdjust(1);
assert.strictEqual(env.els['sp-cntr'].value, '0000000021');
spCntrAdjust(-1);
assert.strictEqual(env.els['sp-cntr'].value, '0000000020');
});
test('spPorAccepted treats a missing PoR and por_ok as accepted', () => {
assert.strictEqual(spPorAccepted(undefined), true);
assert.strictEqual(spPorAccepted({ response_status: 'por_ok' }), true);
+12 -15
View File
@@ -31,7 +31,8 @@ let code = '';
const ASYNC_FNS = ['cardsAdd', 'cardsImport', 'cardsRemove'];
for (const fn of ['cardsFormValues', 'cardsClearForm', 'cardsEdit',
'cardsAdd', 'cardsImport', 'cardsRemove', 'ramCardIdxAfterRemove',
'spPresetIdx', 'spCntrSyncPreset', 'spCntrLocalSync', 'ramSaveCntr',
'spPresetIdx', 'spPresetCounterValue', 'spCntrPlaceholder', 'spCntrEffective',
'spCntrAhead', 'spCntrLocalSync', 'ramSaveCntr',
'cardsApplyFields', 'cardsApply', 'ramApplyCard',
'cardsScp80Complete', 'cardsScp81Complete', 'cardsAdmPresent',
'spTarKeyForPack', 'spPresetTar', 'spTarListRender', 'packToSp',
@@ -415,29 +416,25 @@ test('import posts the entries to the server store', async () => {
assert.strictEqual(apiCalls.length, 0);
});
test('the SCP80 counter edit is written to the store, a reported counter only locally', () => {
test('the SCP80 counter field is an override - an edit is never written to the store', () => {
const els = setup();
globalThis.cards = [{ id: 'abc123', name: 'C', keysets: [
{ kic: '15', kid: '15', kicKey: 'AA', kidKey: 'BB', cntr: '0000000001' }] }];
els['sp-card-sel'].value = '0';
els['sp-kic-hex'].value = '15';
els['sp-kid-hex'].value = '15';
els['sp-cntr'].value = '0000000009';
assert.strictEqual(spCntrSyncPreset(), true);
assert.strictEqual(cards[0].keysets[0].cntr, '0000000009');
assert.strictEqual(apiCalls.length, 1);
assert.strictEqual(apiCalls[0].path, '/api/presets/update');
assert.strictEqual(apiCalls[0].body.id, 'abc123');
assert.strictEqual(apiCalls[0].body.fields.keysets[0].cntr, '0000000009');
// a counter the server already persisted: display only, no second write
apiCalls = [];
els['sp-cntr'].value = '0000000009'; // an explicit override
// typing alone writes nothing (no spCntrSyncPreset anymore, v3.20.0)
assert.strictEqual(apiCalls.length, 0);
// a counter the server persisted: the local copy moves forward, display only
spCntrLocalSync('000000000A');
assert.strictEqual(cards[0].keysets[0].cntr, '000000000A');
assert.strictEqual(apiCalls.length, 0);
// no preset selected: nothing to write
els['sp-card-sel'].value = '';
assert.strictEqual(spCntrSyncPreset(), false);
assert.strictEqual(apiCalls.length, 0);
// and the copy never regresses (the store is monotonic)
spCntrLocalSync('0000000005');
assert.strictEqual(cards[0].keysets[0].cntr, '000000000A');
// the override in the field is untouched by the copy sync
assert.strictEqual(els['sp-cntr'].value, '0000000009');
});
test('applying a preset uses the TAR of the current operation and seeds the SPI1 from its MSL', () => {
+2 -1
View File
@@ -979,8 +979,9 @@ test('every SCP80/RAM flow checks the low counter and stops', () => {
assert.ok(sync.includes("own = view === 'sp'"), sync);
assert.ok(sync.includes('kvnOf(own)'), sync);
assert.ok(sync.includes('kvnOf(other)'), sync);
assert.ok(sync.includes("getElementById('sp-cntr')"), sync);
assert.ok(sync.includes('spKeysetSync()'), 'the keyset labels must refresh');
assert.ok(sync.includes('spCntrPlaceholder()'),
'the stored value must refresh the field placeholder (the field stays an override)');
assert.ok(sync.includes("ramListingSpi2('40')"),
'the RAM view must probe with the RAM listing transport (a PoR is required)');
assert.ok(sync.includes('data.counter_saved'),
+4 -1
View File
@@ -29,6 +29,7 @@ function extractFunc(src, name) {
let code = '';
for (const fn of ['berLenStr', 'ramDeleteApdu', 'ramIncrementCntr', 'ramSaveCntr',
'getRamSpParams', 'spPorAccepted', 'ramRemoteSwOk', 'ramShowProgress',
'spPresetIdx', 'spPresetCounterValue', 'spCntrPlaceholder', 'spCntrAhead',
'ramHideProgress', 'ramDeleteFromExplorer',
'spCntrLow', 'ramCntrLowHtml', 'ramCntrLowPresetIdx', 'ramCntrLowView', 'ramShowCntrLow',
'escHtml', 'esc',
@@ -94,7 +95,9 @@ test('accepted delete persists the consumed counter and drops the record', async
assert.strictEqual(calls.sent.spi2, '01', 'the computed SPI2 byte must be used');
assert.strictEqual(cards[0].keysets[0].cntr, '0000000006',
'the preset must carry the counter the card consumed');
assert.strictEqual(els['sp-cntr'].value, '0000000006');
// the form field is an override (empty = auto, the server seeds it); the
// operation only syncs the local preset copy, never the field (v3.20.0)
assert.strictEqual(els['sp-cntr'].value, '0000000005');
assert.strictEqual(calls.sent.preset_id, 'preset-1',
'the operation must name the server-side preset that persists the counter');
assert.deepStrictEqual(calls.removed, { aid: 'F0414C46416101', cascade: false });
+2
View File
@@ -30,6 +30,8 @@ const FNS = ['hexToBytes', 'bytesToHex', 'des3Keys', 'des3EncryptBlock', 'des3Cb
'xorBytes', 'zeroPad', 'crc32Bytes', 'cbcMac', 'aesCbcEncrypt', 'aesShiftLeft1', 'aesCmacSubkeys',
'aesCmac', '_genSpBuild', 'genSp', 'spNextCntr', 'scp80SegmentInfo', 'spSizeInfoText',
'spShowSizeInfo',
// the counter of a built packet: typed override, else the preset's (v3.20.0)
'spCntrEffective', 'spPresetCounterValue',
// the key-version guard genSp runs before building (TS 102 225 A.2)
'spKeysetKvnOf', 'spKeysetList', 'spKeysetFor', 'spKeysetCheck',
'spPresetIdx', 'spKeysetGuard'];